服务器具有Microsoft Office 2003.代码如下
在aspx页面
<asp:UpdatePanel ID="UpdatePanel2" runat="server">
<ContentTemplate>
<asp:LinkButton ID="ExportExcel" runat="server" OnClick="ExportTabletoExcel_Click" OnClientClick="ExportTableJqueryMethod">ExportExcel</asp:LinkButton>
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="ExportExcel" />
</Triggers>
</asp:UpdatePanel>
在Code背后
using Excel1= Microsoft.Office.Interop.Excel;
...
protected void ExportTabletoExcel_Click(object sender, EventArgs e)
{
Excel1.Application excelApp = new Excel1.Application();
...//Adding Data to Excel
excelWorkBook.SaveAs(path, Excel1.XlFileFormat.xlWorkbookNormal);
excelWorkBook.Close();
...//to download
HttpContext.Current.Response.ContentType = "application/xls";
HttpContext.Current.Response.AppendHeader("content-disposition", "attachment; > filename=ExportedExcel.xls");
HttpContext.Current.Response.WriteFile(path + ".xls");
}
在Web.config中<add assembly="Microsoft.Office.Interop.Excel, Version=11.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c"/>
点击Visual Studio,excel下载就好了。但是在服务器上运行相同内容时刷新页面并且没有excel下载。
我的代码如下所示:
使用System.Web.UI.WebControls;使用Excel = Microsoft.Office.Interop.Excel; ......私有Excel.Workbook GenerateExcel(){string excelFileName = HttpContext.Current.Server.MapPath(“〜/ App_Data / TestFile.xlsx”); Excel.Application excel = null; Excel.Workbook excelworkBook = null;试试{excel = new Excel.Application(); excel.Visible = false; excel.DisplayAlerts = false;
//create two sheets AAA & BBB
excelworkBook = excel.Workbooks.Add();
Excel.Worksheet excelSheet1 = (Excel.Worksheet)excelworkBook.ActiveSheet;
excelSheet1.Name = "AAA";
Excel.Worksheet excelSheet2 = (Excel.Worksheet)excelworkBook.Worksheets.Add();
excelSheet2.Name = "BBB";
DataTable dataTable = GetTable();
// now we resize the columns
Excel.Range excelCellrange1 = excelSheet1.Range[excelSheet1.Cells[1, 1], excelSheet1.Cells[dataTable.Rows.Count, dataTable.Columns.Count]];
excelCellrange1.EntireColumn.AutoFit();
//Now fill excelSheet1 up with data
int row = 1;
int col = 1;
foreach (DataRow r in dataTable.Rows)
{
for (int j = 0; j < dataTable.Columns.Count; j++ )
{
excelSheet1.Cells[row, col] = r[j];
col++;
}
row++;
}
//Now fill excelSheet2
row = 1;
col = 1;
foreach (DataRow r in dataTable.Rows)
{
for (int j = 0; j < dataTable.Columns.Count; j++)
{
excelSheet2.Cells[row, col] = r[j];
col++;
}
row++;
}
}
catch (System.Exception ex)
{
}
finally
{
excelworkBook.SaveAs(excelFileName);
excel.Quit();
excel = null;
excelworkBook = null;
FileInfo file = new FileInfo(excelFileName);
if (file.Exists)
{
Response.Clear();
Response.AppendHeader("Content-Disposition", "attachment; filename=" + file.Name);
Response.AddHeader("Content-Length", file.Length.ToString());
Response.TransmitFile(file.FullName);
Response.Flush();
Response.End();
}
}
return excelworkBook;
}