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();

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM