62,046
社区成员
发帖
与我相关
我的任务
分享
private static void DownloadFile(System.Web.UI.Page page, string targetFile)
{
FileInfo DownloadFile = new FileInfo(targetFile);
page.Response.Clear();
page.Response.ClearHeaders();
page.Response.Buffer = false;
page.Response.ContentType = "application/octet-stream";
page.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(DownloadFile.FullName, System.Text.Encoding.UTF8));
page.Response.AppendHeader("Content-Length", DownloadFile.Length.ToString());
page.Response.WriteFile(DownloadFile.FullName);
page.Response.Flush();
page.Response.End();
}
private static void ToExcel(System.Web.UI.Page page, System.Data.DataTable dataSource)
{
string targetFile = ConfigurationManager.AppSettings["Exportfile"].ToString();
if (File.Exists(targetFile))
{
File.Delete(targetFile);
}
ApplicationClass xlApp = new ApplicationClass();
xlApp.Application.Workbooks.Add(true);
xlApp.Visible = false;
object missing = System.Reflection.Missing.Value;
Workbook xlBook = xlApp.Workbooks[1];
Worksheet xlSheet = (Worksheet)xlBook.ActiveSheet;
//设置标题列
for (int i = 0; i < dataSource.Columns.Count; i++)
{
xlSheet.Cells[1, i + 1] = dataSource.Columns[i].ColumnName;
}
//向Excel插入数据
for (int i = 0; i < dataSource.Rows.Count; i++)
{
for (int j = 0; j < dataSource.Columns.Count; j++)
{
xlSheet.Cells[i + 2, j + 1] = dataSource.Rows[i][j].ToString();
xlSheet.get_Range(xlSheet.Cells[1, j + 1], xlSheet.Cells[1, j + 1]).Borders.LineStyle = 1;
xlSheet.get_Range(xlSheet.Cells[i + 2, j + 1], xlSheet.Cells[i + 1, j + 1]).Borders.LineStyle = 1;
}
}
//设置Excel单元格为最适应宽度
xlSheet.get_Range(xlSheet.Cells[1, 1], xlSheet.Cells[dataSource.Rows.Count, dataSource.Columns.Count]).Select();
xlSheet.get_Range(xlSheet.Cells[1, 1], xlSheet.Cells[dataSource.Rows.Count, dataSource.Columns.Count]).Columns.AutoFit();
//另存文件到指定路径下
xlBook.SaveAs(targetFile, missing, missing, missing, missing, missing, XlSaveAsAccessMode.xlNoChange, missing, missing, missing, missing, missing);
//关闭文件
xlBook.Close(false, targetFile, true);
xlApp.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlSheet);
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlBook);
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp);
//强制释放无用资源
GC.Collect();
DownloadFile(page, targetFile);
}