打开并更改 Excel 文件后,我尝试使用以下方法保存它:
excelApp.ActiveWorkbook.Save();
但是数据似乎没有保存。
private void ExportResultsToExcel()
{
string fullFilename = Regex.Match(Path, @".*\\([^\\]+$)").Groups[1].Value;
string fileName = fullFilename.Substring(0, fullFilename.Length - 5);
var templatePath = Path.Replace(fileName, "SolutionTemplate");
var solutionPath = Path.Replace(fileName, fileName+"_Solution");
System.IO.File.Copy(templatePath, solutionPath);
var excelApp = new Excel.Application();
var workbooks = excelApp.Workbooks;
var workbook = workbooks.Open(solutionPath, 0, true, 5, "", "", true,
XlPlatform.xlWindows, "\t", false,
false, 0, true, 1, 0);
var workSheets = workbook.Worksheets;
var workSheet = (Worksheet) workSheets.Item[1];
var rowIndex = 2;
excelApp.DisplayAlerts = false;
excelApp.ScreenUpdating = false;
excelApp.Visible = false;
excelApp.UserControl = false;
excelApp.Interactive = false;
foreach (var product in DemandData.Keys)
{
workSheet.Cells[rowIndex, 1] = product;
workSheet.Cells[rowIndex, 2] = Result[product][0];
workSheet.Cells[rowIndex, 3] = Result[product][1];
workSheet.Cells[rowIndex, 4] = Result[product][2];
workSheet.Cells[rowIndex, 5] = Result[product][3];
workSheet.Cells[rowIndex, 6] = Result[product][4];
workSheet.Cells[rowIndex, 7] = Result[product][5];
workSheet.Cells[rowIndex, 8] = Result[product][6];
workSheet.Cells[rowIndex, 9] = Result[product][7];
workSheet.Cells[rowIndex, 10] = Result[product][8];
workSheet.Cells[rowIndex, 11] = Result[product][9];
workSheet.Cells[rowIndex, 12] = Result[product][10];
workSheet.Cells[rowIndex, 13] = Result[product][11];
workSheet.Cells[rowIndex, 14] = Result[product][12];
rowIndex++;
}
int hWnd = excelApp.Application.Hwnd;
//workbook.Save();
excelApp.ActiveWorkbook.Save();
Marshal.ReleaseComObject(workSheets);
Marshal.ReleaseComObject(workSheet);
Marshal.ReleaseComObject(workbooks);
Marshal.ReleaseComObject(workbook);
workbook.Close();
excelApp.Quit();
TryKillProcessByMainWindowHwnd(hWnd);
}