zoukankan      html  css  js  c++  java
  • 【原创】MyXls导出Excel (适用于Winform/WebForm)

    Excel文章我已经写了两篇,有时间的可以去看一看。今天再说一种实现导出Excel的第三方组件MyXls组件。

    我引用百度百科对它的描述:

    MyXls是一个操作Excel的开源类库,支持设置字体、列宽、行高(由BOSSMA实现)、合并单元格、边框、背景颜色、数据类型、自动换行、对齐方式等,通过众多项目的使用表现,

    证明MyXls对于创建
    简单格式的Excel文件十分快捷方便。 MyXLS是一个导出Excel的好工具,速度快,体积小,而且也不用担心使用Com生成Excel时资源释放的问题了

    有机会可以去官方下载相关代码,我这里直接给出这个dll的下载地址

    MyXls.dll下载

    我还根据前两篇文章的实现功能,使用MyXls来实现一下。

    如果没有看前两启篇文章的我再说一下实现功能:

    (1)Excel行数的限制,office2003的行数为65536行。如果超过这个行数应该再来一个sheet

    (2)导出数据慢的问题

    (3)如果用微软的Excel插件,还必须在服务器安装office,用此插件就可以解决了。

    代码实现开始:

    (1)下载dll,在你的程序中添加引用,并用引用命名空间

    using org.in2bits.MyXls;
    using System.IO;

    (2)创建Excel工单薄

     XlsDocument xls = new XlsDocument();

      Worksheet sheet = xls.Workbook.Worksheets.Add("新Sheet");

    (3)添加内容到sheet中

    sheet.Cells.Add(插入单元格的行,插入单元格的列, 插入的值);

    例如:

    sheet.Cells.Add(1,1, "我是第一行第一列的值");

    它的Add方法有四个重载,我这里只讲本例中用到的方法。        

    (4)保存

    //第一种保存方式:适用于Winform / WebForm
                        string strFilePath = System.AppDomain.CurrentDomain.BaseDirectory;
                        xls.FileName =sheetName;
                        xls.Save(strFilePath);               
                        xls = null;
    
    
                    //第二种保存方式适用于WebForm,可以选择保存路径
                        using (MemoryStream ms = new MemoryStream())
                        {
                            xls.Save(ms);
                            ms.Flush();
                            ms.Position = 0;
    
                            xls = null;
                            HttpResponse response = System.Web.HttpContext.Current.Response;
                            response.Clear();
                            response.Charset = "UTF-8";
                            response.ContentType = "application/vnd-excel";//"application/vnd.ms-excel";   
                            System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment; filename=" + xlsname));
                            //System.Web.HttpContext.Current.Response.WriteFile(fi.FullName);                    
                            byte[] data = ms.ToArray();
                            System.Web.HttpContext.Current.Response.BinaryWrite(data);
                        }
    
     

    基本代码要点,解释完毕,我把完整代码贴出来,供大家参考:

      1   /// <summary>
      2         /// 第三方插件MyXls导出Excel数据
      3         /// </summary>
      4         /// <param name="dt">数据源</param>
      5         /// <param name="sheetName">sheet表单名称</param>
      6         /// <param name="xlsname">生成Excel的名称</param>
      7         /// <returns>返回是否成功信息</returns>
      8         public static string DataTableToExcel(System.Data.DataTable dt,string sheetName, string xlsname)
      9         {
     10             string msg = "";           
     11             XlsDocument xls = new XlsDocument();
     12             try
     13             {              
     14                 //最大行限制
     15                 int MaxRowCount = 60000;
     16 
     17                 int rowCount = dt.Rows.Count;
     18                 int colCount = dt.Columns.Count;
     19 
     20 
     21                 if (rowCount > 0 && rowCount <= MaxRowCount)
     22                 {
     23                     Worksheet sheet = xls.Workbook.Worksheets.Add(sheetName);
     24                    
     25                     for (int j = 0; j < colCount; j++)
     26                     {
     27                         sheet.Cells.Add(1, j + 1, dt.Columns[j].ColumnName.ToString());     
     28                         
     29                     }
     30 
     31                     for (int j = 0; j < rowCount; j++)
     32                     {
     33                      
     34                         for (int k = 0; k < colCount; k++)
     35                         {
     36                             sheet.Cells.Add(j + 2, k + 1, dt.Rows[j][k].ToString());                            
     37                         }
     38                     }
     39                 }
     40                 else //超过sheet表单的就再创适sheet表单
     41                 {
     42                     int sheetCount = 1; //sheet表单个数
     43                     if (rowCount % MaxRowCount == 0)
     44                     {
     45                         sheetCount = rowCount / MaxRowCount;
     46                     }
     47                     else
     48                     {
     49                         sheetCount = rowCount / MaxRowCount + 1;
     50                     }
     51 
     52                     int Flag = 1;
     53                     for (var m = 0; m < sheetCount; m++)
     54                     {
     55                         //添加一个sheet表单                       
     56                         Worksheet sheet = xls.Workbook.Worksheets.Add("" + (m + 1) + "页数据");
     57                         //如果不是最后一个表单的话 并且最后一个sheet表单数据不等于60000
     58                         if (Flag == sheetCount && (rowCount % MaxRowCount != 0))
     59                         {
     60                             int newrowCount = rowCount - ((Flag - 1) * MaxRowCount); //最后一个sheet的数据
     61 
     62 
     63                             int RowIndex = 0;
     64              
     65                             for (int j = 0; j < colCount; j++)
     66                             {   
     67                                 sheet.Cells.Add(1, j + 1, dt.Columns[j].ColumnName.ToString());                  
     68                             }
     69 
     70 
     71 
     72                             int startIndex = (Flag - 1) * MaxRowCount;
     73                             for (int n = startIndex; n < startIndex + newrowCount; n++)
     74                             {                               
     75                                 for (int t = 0; t < colCount; t++)
     76                                 {
     77                                     sheet.Cells.Add(RowIndex + 2, t + 1, dt.Rows[n][t].ToString());                 
     78                                 }
     79 
     80                                 RowIndex++;
     81                             }
     82 
     83                         }
     84                         else
     85                         {                         
     86                             for (int j = 0; j < colCount; j++)
     87                             {               
     88                                 sheet.Cells.Add(1, j + 1, dt.Columns[j].ColumnName.ToString());      
     89                             }
     90                             int startIndex = (Flag - 1) * MaxRowCount;
     91                             int rowIndex = 0;
     92                             for (int n = startIndex; n < startIndex + MaxRowCount; n++)
     93                             {
     94                                
     95                                 for (int t = 0; t < colCount; t++)
     96                                 {
     97                                     sheet.Cells.Add(rowIndex + 2, t + 1, dt.Rows[n][t].ToString());                 
     98                                 }
     99                                 rowIndex++;
    100                             }
    101 
    102                         }
    103                         Flag++;
    104                     }
    105 
    106                 }
    107 
    108                 #region 客户端保存
    109                 //第一种保存方式:适用于Winform / WebForm
    110                     string strFilePath = System.AppDomain.CurrentDomain.BaseDirectory;
    111                     xls.FileName =sheetName;
    112                     xls.Save(strFilePath);               
    113                     xls = null;
    114 
    115                 //第二种保存方式适用于WebForm,可以选择保存路径
    116                     //using (MemoryStream ms = new MemoryStream())
    117                     //{
    118                     //    xls.Save(ms);
    119                     //    ms.Flush();
    120                     //    ms.Position = 0;
    121 
    122                     //    xls = null;
    123                     //    HttpResponse response = System.Web.HttpContext.Current.Response;
    124                     //    response.Clear();
    125                     //    response.Charset = "UTF-8";
    126                     //    response.ContentType = "application/vnd-excel";//"application/vnd.ms-excel";   
    127                     //    System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment; filename=" + xlsname));
    128                     //    //System.Web.HttpContext.Current.Response.WriteFile(fi.FullName);                    
    129                     //    byte[] data = ms.ToArray();
    130                     //    System.Web.HttpContext.Current.Response.BinaryWrite(data);
    131                     //}
    132                 #endregion
    133                 
    134             }
    135             catch
    136             {
    137                 xls = null;
    138                 GC.Collect();
    139                 return "出现异常";
    140             }
    141             finally
    142             {
    143                 xls = null;
    144                 GC.Collect();
    145             }
    146 
    147             return msg;
    148         }

     转载的请注原创地址,谢谢。

  • 相关阅读:
    关于js中this的指向问题
    关于css垂直水平居中的几种方法
    个人第一个jquery插件(tips)
    css3实现虚拟三角形
    js-关于唯一ID的创建
    面试题
    new Promise()
    JSON.parse()、JSON.stringify()和eval()的作用
    vue-router路由导航
    NodeJS
  • 原文地址:https://www.cnblogs.com/yxhblog/p/2539894.html
Copyright © 2011-2022 走看看