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);
}
}
}
}
相关文章:
-
2022-12-23
-
2022-12-23
-
2022-12-23
-
2022-12-23
-
2021-11-18
猜你喜欢
-
2022-03-10
-
2021-12-17
-
2021-11-18
-
2021-05-27
-
2022-01-29
-
2021-06-22
相关资源
-
下载
2021-06-06
-
下载
2023-01-19
-
下载
2022-11-30