C# 导出EXCEL 并下载

//导出EXCEL
protected void ExportExcel(System.Data.DataTable dt)
{
if (dt == null || dt.Rows.Count == 0) return;
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
if (xlApp == null)
{
return;
}
System.Globalization.CultureInfo CurrentCI = System.Threading.Thread.CurrentThread.CurrentCulture;
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
Microsoft.Office.Interop.Excel.Workbooks workbooks = xlApp.Workbooks;
Microsoft.Office.Interop.Excel.Workbook workbook = workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];
long totalCount = dt.Rows.Count;

worksheet.Cells[1, 1] = "序号";
worksheet.Cells[1, 2] = "姓名";
worksheet.Cells[1, 3] = "电话";
worksheet.Cells[1, 4] = "商品";
worksheet.Cells[1, 5] = "网点";

for (int r = 0; r < dt.Rows.Count; r++)
{
worksheet.Cells[r + 2, 1] = (r + 1).ToString();
worksheet.Cells[r + 2, 2] = dt.Rows[r]["f_Name"].ToString();
worksheet.Cells[r + 2, 3] = dt.Rows[r]["f_Tel"].ToString();
worksheet.Cells[r + 2, 4] = dt.Rows[r]["f_Commodity"].ToString();
worksheet.Cells[r + 2, 5] = dt.Rows[r]["f_Address"].ToString();
}

Microsoft.Office.Interop.Excel.Range range = worksheet.Columns;
range.Columns.AutoFit();//Excel 列自适应宽度

xlApp.Visible = true;
workbook.Saved = true;
workbook.SaveCopyAs(Server.MapPath("../Files/excel.xls"));

workbook.Close(true, Type.Missing, Type.Missing);
workbook = null;
xlApp.Quit();
xlApp = null;
}
}

//下载

public void DownloadFile(string fileRpath)
{

Response.ClearHeaders();
Response.Clear();
Response.Expires = 0;
Response.Buffer = true;
Response.AddHeader("Accept-Language", "zh-tw");
string name = System.IO.Path.GetFileName(fileRpath);
System.IO.FileStream files = new FileStream(fileRpath, FileMode.Open, FileAccess.Read, FileShare.Read);
byte[] byteFile = null;
if (files.Length == 0)
{
byteFile = new byte[1];
}
else
{
byteFile = new byte[files.Length];
}
files.Read(byteFile, 0, (int)byteFile.Length);
files.Close();

Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(name, System.Text.Encoding.UTF8));
Response.ContentType = "application/octet-stream;charset=gbk";
Response.BinaryWrite(byteFile);
Response.End();

}

posted on 2016-12-22 11:19  lmx22  阅读(5575)  评论(0编辑  收藏  举报

导航