在项目中需要导入Excel文件,其中需要把Excel格式的数据转换为我们私有格式。
因此需要测试尽可能多的负数,于是乎写了如下的code进行测试:
代码
public void ExcelLoadSave(int targetValue,string fileName)
{
Excel._Application app = new Excel.Application();
app.Visible = false;
Excel.Workbooks wookbooks = app.Workbooks;
Excel._Workbook workbook = app.Workbooks.Open(fileName, Excel.XlUpdateLinks.xlUpdateLinksUserSetting, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "", true, false, true, false, true, Excel.XlCorruptLoad.xlNormalLoad);
Excel._Workbook wookbook = wookbooks.get_Item(1);
Excel.Sheets sheets = wookbook.Sheets;
Excel._Worksheet ExcelSheet = (Excel.Worksheet)sheets.get_Item(1);
Excel.Range CellRange = (Excel.Range)ExcelSheet.Cells[1, 1];
CellRange.Value2 = targetValue;
workbook.Save();
wookbook.Close(false, Missing.Value, Missing.Value);
app.Quit();
KillExcelProcess();
}
private void KillExcelProcess()
{
Process[] pss = Process.GetProcesses();
for (int i = 0; i < pss.Length; i++)
{
if (pss[i].ProcessName == "EXCEL.EXE")
{
pss[i].Kill();
}
}
}
{
Excel._Application app = new Excel.Application();
app.Visible = false;
Excel.Workbooks wookbooks = app.Workbooks;
Excel._Workbook workbook = app.Workbooks.Open(fileName, Excel.XlUpdateLinks.xlUpdateLinksUserSetting, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "", true, false, true, false, true, Excel.XlCorruptLoad.xlNormalLoad);
Excel._Workbook wookbook = wookbooks.get_Item(1);
Excel.Sheets sheets = wookbook.Sheets;
Excel._Worksheet ExcelSheet = (Excel.Worksheet)sheets.get_Item(1);
Excel.Range CellRange = (Excel.Range)ExcelSheet.Cells[1, 1];
CellRange.Value2 = targetValue;
workbook.Save();
wookbook.Close(false, Missing.Value, Missing.Value);
app.Quit();
KillExcelProcess();
}
private void KillExcelProcess()
{
Process[] pss = Process.GetProcesses();
for (int i = 0; i < pss.Length; i++)
{
if (pss[i].ProcessName == "EXCEL.EXE")
{
pss[i].Kill();
}
}
}