如何保存由Microsoft.Office.Interop.Excel生成的文件

时间:2019-01-24 13:16:14

标签: asp.net 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();

1 个答案:

答案 0 :(得分:0)

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

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\的{​​{1}}文件夹读/写。