尝试写入Excel工作表时未保存文档/无法访问电子表格

时间:2019-05-01 18:30:02

标签: c# excel com interop xlsx

您好,我正在尝试打开Excel工作表,将其写入,然后保存。在我致电xlWorkbook.SaveAs()之前,所有方法都有效。当outputPath与我打开的文件(inputPath)相同时,出现错误System.Runtime.InteropServices.COMException: 'Cannot access 'spreadsheet.xlsx'.'

当inputPath和outputPath不同时,我得到System.Runtime.InteropServices.COMException: 'Document not saved.'

这是我的代码。我不知道怎么了。任何帮助表示赞赏。

            object misValue = Type.Missing;

            Excel.Application xlApp = new Excel.Application {
                Visible = true
            };
            xlApp.DisplayAlerts = false;
            string outputPath = filePath.Text + fileName.Text;
            string inputPath = templateName.Text;

            Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(inputPath, misValue, false, misValue, misValue, misValue, true, misValue, misValue, true,
                misValue, misValue, misValue, misValue, misValue);

            Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1];


            xlWorksheet.Cells[4, 3].Value = customer.Text;
            xlWorksheet.Cells[7, 3].Value = workOrder.Text;

            xlWorkbook.SaveAs(outputPath, Excel.XlFileFormat.xlWorkbookDefault, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlNoChange, 
                misValue, misValue, misValue, misValue, misValue);


            xlWorkbook.Close(true, outputPath, misValue);
            xlApp.Quit();

            Marshal.ReleaseComObject(xlWorkbook);
            Marshal.ReleaseComObject(xlWorksheet);
            Marshal.ReleaseComObject(xlApp);

            GC.Collect();
            GC.WaitForPendingFinalizers();

0 个答案:

没有答案