using Microsoft.Office.Interop.Excel;
namespace FileHandler
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](/Images/OutliningIndicators/ContractedBlock.gif)
{
public class ExcelFile
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
public ExcelFile(string fileName)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
if(!Initial())
return;
excelFileName = fileName;
//加入新的WorkBook
//获取WorkBooks集合
workbooks = excelApp.Workbooks;
if(!System.IO.File.Exists(fileName))
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{//create a new xls file(XlWBATemplate.xlWBATWorksheet
workbook = workbooks.Add(XlWBATemplate.xlWBATWorksheet);
}
else
//*修改原有文件
workbook = workbooks.Add(excelFileName);
//获取WorkSheets集合
sheets = workbook.Worksheets;
worksheet = (Worksheet) sheets.get_Item(1);
if (worksheet == null)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
MessageBox.Show("worksheet is null!","Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
public void Dispose()
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
if(isInitialed && excelApp != null)
excelApp.Quit();
}
public bool Initial()
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
if(!isInitialed)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
excelApp = new Microsoft.Office.Interop.Excel.Application();
if (excelApp == null)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
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)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
worksheet.Cells[row, column] = val;
}
public object Read(int row, int column)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
return worksheet.Cells[row, column];
}
public void Save()
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
if(!workbook.Saved)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
workbook.Close(true,excelFileName,true);
}
}
}
}