导出word excel 方法

时间:2023-02-07 12:10:53

---导出excel

public static void DataTableToExcelXjd(DataTable dt, string Title, string TmpColsName)
{
HttpResponse resp = System.Web.HttpContext.Current.Response;
string ExcelName = Title + DateTime.Now.ToString("yyyyMMddHHmmss");
resp.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
resp.AppendHeader("Content-Disposition", "attachment;filename=" + ExcelName + ".xls");
string colHeaders = "", ls_item = "";
DataRow[] myRow = dt.Select();//可以类似dt.Select("id>10")之形式达到数据筛选目的
int cl = dt.Columns.Count;
string[] arrname = TmpColsName.Split(',');
//取得数据表各列标题,各标题之间以t分割,最后一个列标题后加回车符
//添加网格
resp.Write("<html xmlns:x=\"urn:schemas-microsoft-com:office:excel\"><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />" +
"<!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>123</x:Name><x:WorksheetOptions><x:Print><x:ValidPrinterInfo /></x:Print></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table><tr> ");

colHeaders +="</tr>";
colHeaders += string.Format("<tr><th width='20'></th><th colspan='12' height='50' style='border:1px solid black;'>场馆每日巡检单(PC/打复印)</th></tr>");
colHeaders += string.Format("<tr><th></th><th colspan='12' height='40' align='left' style='border-left:1px solid black;border-right:1px solid black;'>123: ___________&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;456: ____________</th></tr>");

----根据情况变化html

resp.Write(strb);--strb是html
resp.Write("</table></body></html>");
resp.End();
}

---导出word

HttpResponse resp = System.Web.HttpContext.Current.Response;
string ExcelName = Title + DateTime.Now.ToString("yyyyMMddHHmmss");
resp.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
resp.AppendHeader("Content-Disposition", "attachment;filename=" + ExcelName + ".doc");
string colHeaders = "", ls_item = "";
DataRow[] myRow = dt.Select();//可以类似dt.Select("id>10")之形式达到数据筛选目的
int cl = dt.Columns.Count;
string[] arrname = TmpColsName.Split(',');
//取得数据表各列标题,各标题之间以t分割,最后一个列标题后加回车符
//添加网格
resp.Write("<html xmlns=\"urn:schemas-microsoft-com:office:word\"><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">"+"<meta name=ProgId content=Word.文档><meta name=Generator content=\"Microsoft Word 9\"><meta name=Originator content=\"Microsoft Word 9\"></head><body lang=ZH-CN link=blue vlink=purple style='tab-interval:21.0pt;text-justify-trim:punctuation'><div class="Section1" style='layout-grid:15.6pt'>");

resp.Write(strb);---strb是html
resp.Write("</div></body></html>");
resp.End();