您现在的位置是:首页 >学无止境 >C#DataTable 导出到Excel的几种方式网站首页学无止境
C#DataTable 导出到Excel的几种方式
将DataTable导出是常见的需求,可以调用以下几种类方法进行导出。
1.适用于web的字符流导出方式
private static void DataTableToExcel(DataTable dt, string saveName)
{
DataGrid dgExcel = new DataGrid();
dgExcel.DataSource = dt;
dgExcel.DataBind();
HttpContext.Current.Response.Charset = "GB2312";
string fileName = HttpUtility.UrlEncode(saveName, System.Text.Encoding.UTF8);
string str = "attachment;filename=" + fileName + ".xls";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
HttpContext.Current.Response.ContentType = "application/ms-excel";
HttpContext.Current.Response.AppendHeader("content-disposition", str);
//如需添加其他标头或新增自定义行
//StringWriter sw_title = new StringWriter();
//HtmlTextWriter htmlTextWriter_title = new HtmlTextWriter(sw_title);
//htmlTextWriter_title.AddStyleAttribute(HtmlTextWriterStyle.FontSize, "20px");//样式
//Label label1 = new Label();
//label1.Text = "在原有DataDable上新增标头 自定义行";
//label1.RenderControl(htmlTextWriter_title);
StringWriter sw = new StringWriter();
HtmlTextWriter htmTextWriter = new HtmlTextWriter(sw);
dgExcel.RenderControl(htmTextWriter);
HttpContext.Current.Response.Write("<meta http-equiv="content-type" content="application/vnd.ms-excel; charset=utf-8"/>" + sw.ToString());
HttpContext.Current.Response.End();
}
2.适用于Client的DataTable导出方式
(1)以字符流将DataTable导出csv格式,不需要引用Microsoft.Excel控件
///dt 要导出的DataTable filePath导出路径 tableheader表格头名称 columnname字段名称(可遍历DataTable ColumnName得出,中间以逗号分隔如:字段1,字段2,...字段N)
private static bool DataTableToExcel(DataTable dt, string filePath, string tableheader, string columname)
{
try
{
string bufferLine = "";
StreamWriter swObj = new StreamWriter(filePath, false, System.Text.Encoding.UTF8);
swObj.WriteLine(tableheader);
swObj.WriteLine(columname);
for (int i = 0; i < dt.Rows.Count; i++)
{
bufferLine = "";
for (int j = 0; j < dt.Columns.Count; j++)
{
if (j > 0)
{
bufferLine += ",";
}
String handleStr = dt.Rows[i][j].ToString();
//特殊符号转义,回车、换行
if (dt.Rows[i][j].ToString().Contains("
"))
{
handleStr = dt.Rows[i][j].ToString().Replace("
", ";");
}
if (dt.Rows[i][j].ToString().Contains("
") || dt.Rows[i][j].ToString().Contains("
"))
{
handleStr = dt.Rows[i][j].ToString().Replace("
", "").Replace("
","");
}
//特殊符号转义,逗号
if (dt.Rows[i][j].ToString().Contains(","))
{
//双引号
if (dt.Rows[i][j].ToString().Contains("""))
{
handleStr = dt.Rows[i][j].ToString().Replace(""", """");
}
//逗号转义
handleStr = """ + handleStr + """;
}
bufferLine += handleStr;
}
swObj.WriteLine(bufferLine);
}
swObj.Close();
return true;
}
catch
{
return false;
}
}
(2)调用Microsoft.Office.Interop.Excel导出将DataTable导出Excel
///filepath导出路径
private static bool DataTableToExcel(DataTable dt,string filepath)
{
bool flag = false;
try
{
System.Reflection.Missing miss = System.Reflection.Missing.Value;
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
excel.Application.Workbooks.Add(true);
excel.Visible = false;
if (excel != null)
{
Microsoft.Office.Interop.Excel.Workbooks books = (Microsoft.Office.Interop.Excel.Workbooks)excel.Workbooks;
Microsoft.Office.Interop.Excel.Workbook book = (Microsoft.Office.Interop.Excel.Workbook)books.Add(miss);
Microsoft.Office.Interop.Excel.Worksheet sheet = (Microsoft.Office.Interop.Excel.Worksheet)book.ActiveSheet;
sheet.Name = "Sheet";//Sheet名称
//字段名
for (int i = 0; i < tb_result.Columns.Count; i++)
{
excel.Cells[1, i + 1] = dt.Columns[i].ColumnName;
}
//数据
for (int row = 0; row <= dt.Rows.Count - 1; row++)
{
for (int column = 0; column < dt.Columns.Count; column++)
{
try
{
//将数字以文本方式存储,防止第一位为0的数或长数字被Excel省略
if (dt.Rows[row][column].ToString().Trim().Replace("0", "") != "")
{
Convert.ToInt32(dt.Rows[row][column].ToString().Trim().Replace("0", ""));
excel.Cells[row + 2, column + 1].NumberFormatLocal = "@";
excel.Cells[row + 2, column + 1] = dt.Rows[row][column].ToString();
}
}
catch
{
excel.Cells[row + 2, column + 1] = dt.Rows[row][column].ToString();
}
//设置Cells宽度
excel.Cells[row + 2, column + 1].ColumnWidth = dt.Rows[row][column].ToString().Length * 1.5;
}
}
string Version = excel.Version;//获取Excel版本
int FormatNum;
if (Convert.ToDouble(Version) < 12)//97-2003版本
{
FormatNum = -4143;
}
else//其他excel版本
{
FormatNum = 56;
}
sheet.SaveAs(filepath, FormatNum, miss, miss, miss, miss, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, miss, miss, miss);
book.Close(false, miss, miss);
books.Close();
excel.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(sheet);
System.Runtime.InteropServices.Marshal.ReleaseComObject(book);
System.Runtime.InteropServices.Marshal.ReleaseComObject(books);
System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);
GC.Collect();
flag = true;
}
}
catch
{
flag = false;
}
return flag;
}