Excel Handle
/*添加引用COM组件*/
Microsoft Excel 11.0 Object Library
/*引用名称空间*/
using System.Data.OleDb;
using Excel = Microsoft.Office.Interop.Excel;
/*操作Excel文件Read-Write单个数据*/
private string filePath;
private bool GetFilePath()
{
OpenFileDialog ofd=new OpenFileDialog();
ofd.Title="Open Excel File";
ofd.AddExtension=true;
ofd.Multiselect=false;
ofd.Filter = "Excel File(*.xls *.xlsx)|*.xls;*.xlsx";
if (ofd.ShowDialog() == DialogResult.OK)
{
this.filePath = ofd.FileName;
return true;
}
else
return false;
}
private bool ReadWriteExcel()
{
string value;
if(GetFilePath())
{
Excel.Application xlsApplication = new Excel.Application();
Excel.Workbook xlsWorkBook = xlsApplication.Workbooks.Open(this.filePath, Type.Missing,
Type.Missing, Type.Missing,Type.Missing,Type.Missing,Type.Missing, Type.Missing,
Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,
Type.Missing);
Excel.Worksheet xlsWorkSheet = (Excel.Worksheet)xlsWorkBook.Worksheets[1];
Excel.Range xlsRange = (Excel.Range)xlsWorkSheet.Cells[1, 1];
if(xlsRange.Value2!=null)
value=xlsRange.Value2.ToString();
else
value=null;
xlsWorkSheet.Cells[1,1]="abc";
xlsWorkBook.Save();
xlsWorkSheet=null;
xlsWorkBook=null;
xlsApplication.Quit();
xlsApplication=null;
return true;
}
else
return false;
}
评论3