- public void CreateExcel(DataTable dt,string FileName)//HttpResponse Page.Response
- {
- string FileType = "application/ms-excel";
- Response.Clear();
- Response.Charset = "UTF-8";
- Response.Buffer = true;
- Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
- Response.AppendHeader("Content-Disposition", "attachment;filename="" + FileName + ".xls"");
- Response.ContentType = FileType;
- string colHeaders = string.Empty;
- colHeaders = '标题'
- Response.Output.Write(colHeaders);
- colHeaders = string.Empty;
- string ls_item = string.Empty;
- DataRow[] myRow = dt.Select();
- int cl = dt.Columns.Count;
- foreach (DataRow row in myRow)
- {
- int count = 0;
- for (int i = 0; i < cl; i++)
- {
- if (i == (cl - 1))
- {
- ls_item += row[i].ToString() + "\n";
- }
- else
- {
- if(count < 2)
- {
- ls_item = ls_item + "" + row[i].ToString() + "\t";
- }
- else
- {
- ls_item += row[i].ToString() + "\t";
- }
- }
- count++;
- }
- Response.Output.Write(ls_item);
- ls_item = string.Empty;
- }
- Response.Output.Flush();
- Response.End();
- }
复制代码
第二种用HttpContext.Current.Response。这种能够解决导出Excel科学记数法的问题。
这个方法的原文链接https://www.cnblogs.com/JsonShare/p/4872173.html - public void CreateExcel_t(DataTable dt, string FileName) {
- HttpContext.Current.Response.Clear();
- HttpContext.Current.Response.Charset = "UTF-8";
- HttpContext.Current.Response.ContentType = "application/vnd.ms-xls";
- HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" + FileName + ".xls");
- StringBuilder table = new StringBuilder();
- table.Append("<table><tr>");
- for (int j = 0; j < dt.Columns.Count; j++)
- {
- table.Append("<td>");
- table.Append(dt.Columns[i].Caption.ToString());//表格的标题
- table.Append("</td>");
- }
- table.Append("</tr>");
- for (int i = 0 ; i < dt.Rows.Count; i++)
- {
- table.Append("<tr>");
- for (int j = 0; j < dt.Columns.Count; j++)
- {
- table.Append("<td style='vnd.ms-excel.numberformat:@'>");
- table.Append(dt.Rows[i][j].ToString());
- table.Append("</td>");
- }
- table.Append("</tr>");
- }
- table.Append("</table>");
- HttpContext.Current.Response.Write(table);
- HttpContext.Current.Response.End();
- }
复制代码
来源:https://blog.csdn.net/weixin_42353499/article/details/80522734 免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作! |