我正在尝试创建一个excel文件并将其保存在文件系统中。
以下是我该怎么做:
private string CreateExcel(List<ExcelResult> list, string fileName) {
// Create the file in the server
string path = System.Web.Hosting.HostingEnvironment.MapPath("~/Media/Temp/Excel/" + fileName + ".xls");
System.Data.DataTable dt = new System.Data.DataTable();
dt.Columns.Add("SerialNo", typeof(int));
dt.Columns.Add("Code", typeof(string));
foreach (ExcelResult item in list) {
dt.Rows.Add(item.SerialNo, item.Code);
}
Application app = new Application();
Workbook wb = app.Workbooks.Add(Type.Missing);
Worksheet ws = (Worksheet)wb.ActiveSheet;
ws.DisplayRightToLeft = false;
ws.Name = "GiftCards";
ws.Cells[1, 1] = "SerialNo";
ws.Cells[1, 2] = "Code";
int rowcount = 2;
foreach (DataRow datarow in dt.Rows) {
rowcount += 1;
for (int i = 1; i <= dt.Columns.Count; i++)
ws.Cells[rowcount, i] = datarow[i - 1].ToString();
}
try {
wb.SaveAs(path);
wb.Close();
app.Quit();
return fileName + ".xls";
} catch (Exception ex) {
Debug.WriteLine("Exception thrown -> " + ex.Message);
return ex.Message;
}
}
只有在IIS上部署应用程序且本地(iis express)没有任何问题时才会出现错误。
任何想法?