using Microsoft.Office.Interop.Excel;
namespace FileHandler
{
public class ExcelFile
{
public ExcelFile(string fileName)
{
if(!Initial())
return;

excelFileName = fileName;
//加入新的WorkBook
//获取WorkBooks集合
workbooks = excelApp.Workbooks;
if(!System.IO.File.Exists(fileName))
![]()
workbook = workbooks.Add(XlWBATemplate.xlWBATWorksheet);
}
else
//*修改原有文件
workbook = workbooks.Add(excelFileName);

//获取WorkSheets集合
sheets = workbook.Worksheets;
worksheet = (Worksheet) sheets.get_Item(1);
if (worksheet == null)
{
MessageBox.Show("worksheet is null!","Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}

}

public void Dispose()
{
if(isInitialed && excelApp != null)
excelApp.Quit();
}

public bool Initial()
{
if(!isInitialed)
{
excelApp = new Microsoft.Office.Interop.Excel.Application();
if (excelApp == null)
{
MessageBox.Show("Excel couldn't be started!","Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
excelApp.DisplayAlerts = false;
isInitialed = true;
}
return true;
}
private static Microsoft.Office.Interop.Excel.Application excelApp;
private Microsoft.Office.Interop.Excel.Workbooks workbooks;
private Microsoft.Office.Interop.Excel.Workbook workbook;
private Sheets sheets;
private Worksheet worksheet;
private string excelFileName;
private static bool isInitialed = false;

public void Write(int row, int column, object val)
{
worksheet.Cells[row, column] = val;
}
public object Read(int row, int column)
{
return worksheet.Cells[row, column];
}

public void Save()
{
if(!workbook.Saved)
{
workbook.Close(true,excelFileName,true);
}
}
}
}
相关文章: