首页 > 解决方案 > 如何保存由 Microsoft.Office.Interop.Excel 生成的文件

问题描述

我正在使用 Microsoft Interop.Excel 生成一个 excel 文件。我需要您选择保存位置。我在做 ASP.NET C#。

这是我到目前为止所拥有的:

Application excel = new Application(); 
Workbook wb = excel.Workbooks.Add(XlWBATemplate.xlWBATWorksheet); 
Worksheet ws = (Worksheet)wb.Worksheets.get_Item(1); 
ws.Name = "Nome da Pasta"; 
ws.Cells[1, 1] = "POÇO:"; 
ws.Cells[2, 1] = "CAMPO:"; 
ws.Cells[3, 1] = "PERIODO:"; 
ws.Cells[5, 1] = "DATA HORA (M/D/Y)";
ws.Cells[5, 2] = "PRESSÃO DO POÇO (PSI)"; 
ws.Cells[5, 3] = "RPM DO POÇO"; 
ws.Columns.AutoFit(); 
excel.Quit();

标签: asp.netexcel

解决方案


在您的代码示例中,将其更改如下:

try {
   Application excel = new Application(); 
   Workbook wb = excel.Workbooks.Add       (XlWBATemplate.xlWBATWorksheet); 
   Worksheet ws = (Worksheet)wb.Worksheets.get_Item(1); 
   ws.Name = "Nome da Pasta"; 
   ws.Cells[1, 1] = "POÇO:"; 
   ws.Cells[2, 1] = "CAMPO:"; 
   ws.Cells[3, 1] = "PERIODO:"; 
   ws.Cells[5, 1] = "DATA HORA (M/D/Y)";
   ws.Cells[5, 2] = "PRESSÃO DO POÇO (PSI)"; 
   ws.Cells[5, 3] = "RPM DO POÇO"; 
   ws.Columns.AutoFit(); 
   //Save your file
   wb.SaveAs("c:\temp\SaveExample.xlsx");
   excel.Quit();
} catch (Exception ex) {
   //Log the exception, to NLog, or a file or something.
   //Otherwise, don't use a try/catch. Any error would get
   //logged in the Server's NT Event Log (under Application).
   //If this code doesn't work. Look there for the problem and
   //callstack.
}

最后一件事:您的保存路径必须可由 IIS 使用的同一帐户写入。最简单的(对于我上面的示例)是使C:\Temp\文件夹为Everyone.


推荐阅读