关于C#,ASP.NET 生成Excel表格的两种方式(Datatable转Excel)

个人认为比较好用,比较简单的生成Excel表格的方式有两种,一种为直接写方法,一种为引用Excel

一. 这种方式生成速度比较快,适合大数据量对样式没什么要求的项目,下面上代码

  1. /// <summary>  
  2.    /// Datatable生成Excel表格并返回路径  
  3.    /// </summary>  
  4.    /// <param name="m_DataTable">Datatable</param>  
  5.    /// <param name="s_FileName">文件名</param>  
  6.    /// <returns></returns>  
  7.    public string DataToExcel(System.Data.DataTable m_DataTable, string s_FileName)  
  8.    {  
  9.        string FileName = AppDomain.CurrentDomain.BaseDirectory + ("/Upload/Excel/") + s_FileName + ".xls";  //文件存放路径  
  10.        if (System.IO.File.Exists(FileName))                                //存在则删除  
  11.        {  
  12.            System.IO.File.Delete(FileName);  
  13.        }      
  14.        System.IO.FileStream objFileStream;  
  15.        System.IO.StreamWriter objStreamWriter;  
  16.        string strLine = "";  
  17.        objFileStream = new System.IO.FileStream(FileName, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write);  
  18.        objStreamWriter = new System.IO.StreamWriter(objFileStream, Encoding.Unicode);  
  19.        for (int i = 0; i < m_DataTable.Columns.Count; i++)  
  20.        {  
  21.            strLine = strLine + m_DataTable.Columns[i].Caption.ToString() + Convert.ToChar(9);      //写列标题  
  22.        }  
  23.        objStreamWriter.WriteLine(strLine);  
  24.        strLine = "";  
  25.        for (int i = 0; i < m_DataTable.Rows.Count; i++)  
  26.        {  
  27.            for (int j = 0; j < m_DataTable.Columns.Count; j++)  
  28.            {  
  29.                if (m_DataTable.Rows[i].ItemArray[j] == null)  
  30.                    strLine = strLine + " " + Convert.ToChar(9);                                    //写内容  
  31.                else  
  32.                {  
  33.                    string rowstr = "";  
  34.                    rowstr = m_DataTable.Rows[i].ItemArray[j].ToString();  
  35.                    if (rowstr.IndexOf("\r\n") > 0)  
  36.                        rowstr = rowstr.Replace("\r\n"" ");  
  37.                    if (rowstr.IndexOf("\t") > 0)  
  38.                        rowstr = rowstr.Replace("\t"" ");  
  39.                    strLine = strLine + rowstr + Convert.ToChar(9);  
  40.                }  
  41.            }  
  42.            objStreamWriter.WriteLine(strLine);  
  43.            strLine = "";  
  44.        }  
  45.        objStreamWriter.Close();  
  46.        objFileStream.Close();  
  47.        return FileName;        //返回生成文件的绝对路径  
  48.    }  
二.这种方式速度可能比较 ,但是可以精确定义每行每列数据的样式(在这里行列顺序和Datatable中是相反的,注意一下)

首先要引用命名空间

  1. using Microsoft.Office.Interop.Excel;  

  1. /// <summary>  
  2. /// 将数据表保存到Excel表格中  
  3. /// </summary>  
  4. /// <param name="addr">Excel表格存放地址</param>  
  5. /// <param name="dt">要输出的DataTable</param>  
  6. public string SaveToExcel(string addr, System.Data.DataTable dt)  
  7. {  
  8.     //0.注意:  
  9.     // * Excel中形如Cells[x][y]的写法,前面的数字是列,后面的数字是行!  
  10.     // * Excel中的行、列都是从1开始的,而不是0  
  11.     //1.制作一个新的Excel文档实例  
  12.     Application xlsApp = new Application();  
  13.     xlsApp.DisplayAlerts = false;  
  14.     xlsApp.Workbooks.Add(true);  
  15.     //2.设置Excel分页卡标题  
  16.     xlsApp.ActiveSheet.Name = "明细报表";  
  17.     //3.合并第一行的单元格  
  18.     string temp = "";  
  19.     if (dt.Columns.Count < 26)  
  20.     {  
  21.         temp = ((char)('A' + dt.Columns.Count)).ToString();  
  22.     }  
  23.     else if (dt.Columns.Count <= 26 + 26 * 26)  
  24.     {  
  25.         temp = ((char)('A' + (dt.Columns.Count - 26) / 26)).ToString()  
  26.           + ((char)('A' + (dt.Columns.Count - 26) % 26)).ToString();  
  27.     }  
  28.     else throw new Exception("列数过多");  
  29.     Range range = xlsApp.get_Range("A1", temp + "1");  
  30.     range.ClearContents(); //清空要合并的区域  
  31.     range.MergeCells = true//合并单元格  
  32.     //4.填写第一行:表名,对应DataTable的TableName  
  33.     xlsApp.Cells[1][1] = "明细报表";  
  34.     xlsApp.Cells[1][1].Font.Name = "黑体";  
  35.     xlsApp.Cells[1][1].Font.Size = 25;  
  36.     xlsApp.Cells[1][1].Font.Bold = true;  
  37.     xlsApp.Cells[1][1].HorizontalAlignment = Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter;//居中  
  38.     xlsApp.Rows[1].RowHeight = 60; //第一行行高为60(单位:磅)  
  39.     //5.合并第二行单元格,用于书写表格生成日期  
  40.     range = xlsApp.get_Range("A2", temp + "2");  
  41.     range.ClearContents(); //清空要合并的区域  
  42.     range.MergeCells = true//合并单元格  
  43.     //6.填写第二行:生成时间  
  44.     xlsApp.Cells[1][2] = "报表生成于:" + DateTime.Now.ToString();  
  45.     xlsApp.Cells[1][2].Font.Name = "宋体";  
  46.     xlsApp.Cells[1][2].Font.Size = 15;  
  47.     //xlsApp.Cells[1][2].HorizontalAlignment = 4;//右对齐  
  48.     xlsApp.Cells[1][2].HorizontalAlignment = Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter;//居中  
  49.     xlsApp.Rows[2].RowHeight = 30; //第一行行高为60(单位:磅)  
  50.     //7.填写各列的标题行。从Datatable中拉出来的列标题为数据库中字段,我们把他改成自己的  
  51.     xlsApp.Cells[1][3] = "";  
  52.     xlsApp.Cells[0 + 2][3] = "序号";  
  53.     xlsApp.Cells[1 + 2][3] = "订单号";  
  54.     xlsApp.Cells[1 + 2][3].ColumnWidth = 20;  
  55.     xlsApp.Cells[2 + 2][3] = "店铺账号";  
  56.     xlsApp.Cells[3 + 2][3] = "会员账号";  
  57.     xlsApp.Cells[4 + 2][3] = "商品编号";  
  58.     xlsApp.Cells[5 + 2][3] = "商品名称";  
  59.     xlsApp.Cells[5 + 2][3].ColumnWidth = 20;  
  60.     xlsApp.Cells[6 + 2][3] = "商品规格";  
  61.     xlsApp.Cells[7 + 2][3] = "型号";  
  62.     xlsApp.Cells[7 + 2][3].ColumnWidth = 20;  
  63.     xlsApp.Cells[8 + 2][3] = "单价";  
  64.     xlsApp.Cells[9 + 2][3] = "数量";  
  65.     xlsApp.Cells[10 + 2][3] = "总价";  
  66.     xlsApp.Cells[11 + 2][3] = "时间";  
  67.     xlsApp.Cells[11 + 2][3].ColumnWidth = 45;  
  68.     xlsApp.Rows[3].Font.Name = "宋体";  
  69.     xlsApp.Rows[3].Font.Size = 13;      //设置字号  
  70.     xlsApp.Rows[3].Font.Bold = true;    //粗体  
  71.     xlsApp.Rows[3].HorizontalAlignment = Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter;//居中  
  72.     range = xlsApp.get_Range("A3", temp + "3");  
  73.     range.Interior.ColorIndex = 33;//背景颜色  
  74.     //8.填写DataTable中的数据  
  75.     for (int i = 0; i < dt.Rows.Count; i++)  
  76.     {  
  77.         for (int j = 0; j < dt.Columns.Count; j++)  
  78.         {  
  79.             switch (j)  
  80.             {  
  81.                 case 1: xlsApp.Cells[j + 2][i + 4] = "'" + dt.Rows[i][j]; break;  
  82.                 case 2: xlsApp.Cells[j + 2][i + 4] = "'" + dt.Rows[i][j]; break;  
  83.                 case 3: xlsApp.Cells[j + 2][i + 4] = "'" + dt.Rows[i][j]; break;  
  84.                 case 4: xlsApp.Cells[j + 2][i + 4] = "'" + dt.Rows[i][j]; break;  
  85.                 case 7: xlsApp.Cells[j + 2][i + 4] = "'" + dt.Rows[i][j]; break;  
  86.                 case 11: xlsApp.Cells[j + 2][i + 4] = "'" + Convert.ToDateTime(dt.Rows[i][j]).ToString("yyyy年MM月dd日 hh时mm分ss秒ffff毫秒"); break;  
  87.                 default: xlsApp.Cells[j + 2][i + 4] = dt.Rows[i][j]; break;  
  88.             }  
  89.         }  
  90.     }  
  91.     range = xlsApp.get_Range("A4", temp + (dt.Rows.Count + 3).ToString());  
  92.     range.Interior.ColorIndex = 2; //修改颜色  
  93.     range.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter;  
  94.     //9.描绘边框  
  95.     range = xlsApp.get_Range("A1", temp + (dt.Rows.Count + 3).ToString());  
  96.     range.Borders.LineStyle = 1;  
  97.     range.Borders.Weight = 3;  
  98.     //10.打开制作完毕的表格  
  99.     //xlsApp.Visible = true;  
  100.     //11.保存表格到根目录下指定名称的文件中  
  101.     string path = AppDomain.CurrentDomain.BaseDirectory + ("Upload\\Excel\\" + addr + ".xls");  
  102.     xlsApp.ActiveWorkbook.SaveAs(path);  
  103.     xlsApp.Quit();  
  104.     xlsApp = null;  
  105.     GC.Collect();  
  106.     return path;  
  107. 原文地址:https://blog.csdn.net/u013542549/article/details/71173184
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值