Chinaunix首页 | 论坛 | 博客
  • 博客访问: 178220
  • 博文数量: 89
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 828
  • 用 户 组: 普通用户
  • 注册时间: 2013-10-08 10:44
文章分类
文章存档

2014年(9)

2013年(80)

我的朋友

分类: C#/.net

2013-11-07 14:38:37

   把数据导出excel的应用很广泛,如果使用依赖于excel的com方法,则难度就很大,而且还必须安装excel,否则就不能导出。使用NPOI导出excel很简单,只需要添加一个程序集NPOI.dll的引用就可以,而且不依赖于excel,也就是不需要安装excel。自然比依赖于excel的com方法好很多。
 核心代码
[csharp] view plaincopy
public static void ExportByWeb(List list, string strFileName)  
   {  
       strFileName = DateTime.Now.ToString("yyyyMMddHHmmss") + "-" + strFileName + "-.xls";  
  
       //using (MemoryStream ms = Export(list,false))//生成文件  
       //{  
       //    using (FileStream fs = new FileStream(strFileName, FileMode.Create, FileAccess.Write))  
       //    {  
       //        byte[] data = ms.ToArray();  
       //        fs.Write(data, 0, data.Length);  
       //        fs.Flush();  
       //    }  
       //}  
       HttpContext curContext = HttpContext.Current;//web系统的下载  
       // 设置编码和附件格式     
       curContext.Response.ContentType = "application/vnd.ms-excel";  
       curContext.Response.ContentEncoding = Encoding.UTF8;  
       curContext.Response.Charset = "";  
       curContext.Response.AppendHeader("Content-Disposition",  
           "attachment;filename=" + HttpUtility.UrlEncode(strFileName, Encoding.UTF8));  
       curContext.Response.BinaryWrite(Export(list).GetBuffer());  
       curContext.Response.End();  
   }  
   private static MemoryStream Export(List list)  
   {  
       HSSFWorkbook workbook = new HSSFWorkbook();  
       HSSFSheet sheet = (HSSFSheet)workbook.CreateSheet();//创建Sheet页      
       List ColumnNames = new List();  
       ColumnNames.Add("产品编号");  
       ColumnNames.Add("产品线名称");  
       ColumnNames.Add("可否独立运行");        
       ColumnNames.Add("基本功能价格(元)");  
       ColumnNames.Add("高级功能价格(元)");  
       ColumnNames.Add("合计(元)");  
       //取得列宽     
       int[] arrColumnWidth = new int[ColumnNames.Count];  
       int count = 0;  
       foreach (string item in ColumnNames)  
       {  
           arrColumnWidth[count] = System.Text.Encoding.GetEncoding(936).GetBytes(item).Length * 2;  
           count++;  
       }  
  
       int rowIndex = 0;  
       #region 新建表,填充表头,填充列头,样式  
       if (rowIndex == 65535 || rowIndex == 0)  
       {  
           if (rowIndex != 0)  
           {  
               sheet = (HSSFSheet)workbook.CreateSheet();  
           }  
 
           #region 表头及样式  
           AddTitle(workbook, sheet, ColumnNames.Count, "产品线报价汇总");  
           #endregion  
           #region 列头及样式  
           AddColumnTitle(workbook, sheet, ColumnNames, arrColumnWidth);  
           #endregion  
           rowIndex = 2;  
       }  
       #endregion  
  
       WriteDataRows(list, workbook, ColumnNames.Count, sheet, rowIndex);  
  
  
       using (MemoryStream ms = new MemoryStream())  
       {  
           workbook.Write(ms);  
           ms.Flush();  
           ms.Position = 0;  
           sheet.Dispose();  
           //workbook.Dispose();//一般只用写这一个就OK了,他会遍历并释放所有资源,但当前版本有问题所以只释放sheet     
           return ms;  
       }  
   }  
   ///  
   /// 添加第一行的标题  
   ///
 
   ///  
   ///  
   ///  
   ///  
   private static void AddTitle(HSSFWorkbook workbook, HSSFSheet sheet, int maxColumnCount, string strHeaderText)  
   {  
       HSSFRow headerRow = (HSSFRow)sheet.CreateRow(0);//添加行  
       headerRow.HeightInPoints = 25;//设置高度字体  
       headerRow.CreateCell(0).SetCellValue(strHeaderText);//设置单元格内容  
  
       HSSFCellStyle headStyle = (HSSFCellStyle)workbook.CreateCellStyle();//设置单元格样式  
       headStyle.Alignment = HorizontalAlignment.CENTER;//文字居中  
       HSSFFont font = (HSSFFont)workbook.CreateFont();//设置字体  
       font.FontHeightInPoints = 20;  
       font.Boldweight = 700;  
       headStyle.SetFont(font);  
       headerRow.GetCell(0).CellStyle = headStyle;  
       sheet.AddMergedRegion(new NPOI.SS.Util.Region(0, 0, 0, maxColumnCount - 1));//合并单元格  
   }  
   private static void AddColumnTitle(HSSFWorkbook workbook, HSSFSheet sheet, List ColumnNames, int[] arrColumnWidth)  
   {  
  
       HSSFRow headerRow = (HSSFRow)sheet.CreateRow(1);  
       HSSFCellStyle headStyle = (HSSFCellStyle)workbook.CreateCellStyle();  
       headStyle.Alignment = HorizontalAlignment.CENTER;//文字居中  
       headStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.GOLD.index;//设置前景色  
       headStyle.FillPattern = FillPatternType.ALT_BARS;//  
       HSSFFont font = (HSSFFont)workbook.CreateFont();  
       font.FontHeightInPoints = 10;  
       font.Boldweight = 700;  
       headStyle.SetFont(font);  
       int count = 0; ;  
       foreach (string item in ColumnNames)  
       {  
           headerRow.CreateCell(count).SetCellValue(item);  
           headerRow.GetCell(count).CellStyle = headStyle;  
           //设置列宽     
           sheet.SetColumnWidth(count, (arrColumnWidth[count] + 1) * 256);//设置列宽度  
           count++;  
       }  
   }  
   private static List WriteDataRows(List parentList, HSSFWorkbook workbook, int maxColumnCount, HSSFSheet sheet, int rowIndex)  
   {  
       List listnext = new List();  
       CellStyle style2 = workbook.CreateCellStyle();//设置单元格的样式边框  
       style2.BorderBottom = CellBorderType.THIN;//  
       style2.BottomBorderColor = NPOI.HSSF.Util.HSSFColor.BLACK.index;  
       style2.BorderLeft = CellBorderType.THIN;  
       style2.LeftBorderColor = NPOI.HSSF.Util.HSSFColor.BLACK.index;  
       style2.BorderRight = CellBorderType.THIN;  
       style2.RightBorderColor = NPOI.HSSF.Util.HSSFColor.BLACK.index;  
       style2.BorderTop = CellBorderType.THIN;  
       style2.TopBorderColor = NPOI.HSSF.Util.HSSFColor.BLACK.index;  
       style2.WrapText = true;//根据文本自动调整高度  
       //  HSSFDataFormat formatDate = (HSSFDataFormat)workbook.CreateDataFormat();  
       //    style2.DataFormat = formatDate.GetFormat("yyyy-mm-dd");   
       //    HSSFDataFormat formatMoney = (HSSFDataFormat)workbook.CreateDataFormat();  
       //     style2.DataFormat = formatMoney.GetFormat("#,##0_");  
       foreach (JqueryEasyuiTreeGridNode parent in parentList)  
       {  
           JqueryEasyuiTreeGridNode row = parent;          
  
                   int count = 0;  
                   #region 填充内容  
                   HSSFRow dataRow = (HSSFRow)sheet.CreateRow(rowIndex);  
                   count = 0;  
                   HSSFCell newCell = (HSSFCell)dataRow.CreateCell(count);  
                   newCell.CellStyle = style2;  
                   string drValue = row.PL_Code;  
                   newCell.SetCellValue(drValue);  
                   count++;  
                   newCell = (HSSFCell)dataRow.CreateCell(count);  
                   newCell.CellStyle = style2;  
                   drValue = row.PL_Name;  
                   newCell.SetCellValue(drValue);  
                   count++;  
  
                   newCell = (HSSFCell)dataRow.CreateCell(count);  
                   newCell.CellStyle = style2;  
                   drValue = row.PL_RunFlag;  
                   newCell.SetCellValue(drValue);  
                   count++;                     
                   newCell = (HSSFCell)dataRow.CreateCell(count);  
                   newCell.CellStyle = style2;  
                   newCell.SetCellType(CellType.NUMERIC);  
                   if (row.PL_PRICEDesc.HasValue)  
                   {  
                       newCell.SetCellValue(row.PL_PRICEDesc.Value);  
                   }  
                   else  
                   {  
                       newCell.SetCellValue("");  
                   }  
                   count++;  
                   newCell = (HSSFCell)dataRow.CreateCell(count);  
                   newCell.CellStyle = style2;  
                   newCell.SetCellType(CellType.NUMERIC);  
                   if (row.P_PriceHigh.HasValue)  
                   {  
                       newCell.SetCellValue(row.P_PriceHigh.Value);  
                   }  
                   else  
                   {  
                       newCell.SetCellValue("");  
                   }  
                   count++;  
                   newCell = (HSSFCell)dataRow.CreateCell(count);  
                   newCell.CellStyle = style2;  
                   newCell.SetCellType(CellType.NUMERIC);  
                   newCell.SetCellValue(row.Total_Price);  
                   count++;  
                   //}  
                   #endregion  
  
                   rowIndex++;                  
       }  
       
       return listnext;  
   }  

更有通用性的代码


[csharp] view plaincopy
  1. using NPOI.HPSF;  
  2. using NPOI.HSSF.UserModel;  
  3. using NPOI.SS.UserModel;  
  4. using NPOI.SS.Util;  
[csharp] view plaincopy
  1. public static class ExportToFile{  
  2.         //测试代码1  
  3.        /*      BoBase bll = new BoBase(); 
  4.         List list=new List (); 
  5.         list.AddRange(bll.GetList(string.Empty)); 
  6.         Dictionary FieldNames=new Dictionary (); 
  7.         FieldNames.Add("HT_Code","宿舍类型编码"); 
  8.          FieldNames.Add("HT_ActiveFlag","状态"); 
  9.          FieldNames.Add("HT_Name","宿舍类型名称"); 
  10.  
  11.          ExportToFile.Export(list, "测试", Path.Combine(AppDomain.CurrentDomain.BaseDirectory, DateTime.Now.ToString()+".xls"), FieldNames); 
  12.         * */  
  13.   
  14.          //测试代码2  
  15.         /*   BoBase bl2l = new BoBase(); 
  16.           List list2 = new List(); 
  17.            list2.AddRange(bl2l.GetList(string.Empty)); 
  18.            Dictionary FieldNames2 = new Dictionary(); 
  19.            FieldNames2.Add("SP_Code", "级别编码"); 
  20.            FieldNames2.Add("SP_Name", "级别名称"); 
  21.            FieldNames2.Add("SP_Status", "级别状态"); 
  22.            FieldNames2.Add("SP_ID", "编号"); 
  23.            ExportToFile.Export(list2, "测试", Path.Combine(AppDomain.CurrentDomain.BaseDirectory, DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls"), FieldNames2); 
  24.          *  * */  
  25.         ///      
  26.         /// DataTable导出到Excel文件     
  27.         ///      
  28.         /// 源DataTable     
  29.         /// 表头文本     
  30.         /// 保存位置     
  31.         /// 柳永法   
  32.         public static void Export(List list, string strHeaderText, string strFileName, Dictionary<stringstring> FieldNames)  
  33.         {  
  34.             using (MemoryStream ms = Export(list, strHeaderText,FieldNames))  
  35.             {  
  36.                 using (FileStream fs = new FileStream(strFileName, FileMode.Create, FileAccess.Write))  
  37.                 {  
  38.                     byte[] data = ms.ToArray();  
  39.                     fs.Write(data, 0, data.Length);  
  40.                     fs.Flush();  
  41.                 }  
  42.             }  
  43.         }  
  44.         ///      
  45.         /// 用于Web导出     
  46.         ///      
  47.         /// 源DataTable     
  48.         /// 表头文本     
  49.         /// 文件名     
  50.         /// 柳永法   
  51.         public static void ExportByWeb(List list, string strHeaderText, string strFileName, Dictionary<stringstring> FieldNames)  
  52.         {  
  53.   
  54.             HttpContext curContext = HttpContext.Current;  
  55.             // 设置编码和附件格式     
  56.             curContext.Response.ContentType = "application/vnd.ms-excel";  
  57.             curContext.Response.ContentEncoding = Encoding.UTF8;  
  58.             curContext.Response.Charset = "";  
  59.             curContext.Response.AppendHeader("Content-Disposition",  
  60.                 "attachment;filename=" + HttpUtility.UrlEncode(strFileName, Encoding.UTF8));  
  61.             curContext.Response.BinaryWrite(Export(list, strHeaderText, FieldNames).GetBuffer());  
  62.             curContext.Response.End();  
  63.         }  
  64.         private  static MemoryStream Export(List list, string strHeaderText, Dictionary<stringstring> FieldNames)  
  65.         {  
  66.             HSSFWorkbook workbook = new HSSFWorkbook();  
  67.             HSSFSheet sheet = (HSSFSheet)workbook.CreateSheet();  
  68.             HSSFCellStyle dateStyle = (HSSFCellStyle)workbook.CreateCellStyle();  
  69.             HSSFDataFormat format = (HSSFDataFormat)workbook.CreateDataFormat();  
  70.             dateStyle.DataFormat = format.GetFormat("yyyy-mm-dd");  
  71.   
  72.             //取得列宽     
  73.             int[] arrColWidth = new int[FieldNames.Count];  
  74.             int count = 0;  
  75.             foreach (KeyValuePair<stringstring> item in FieldNames)  
  76.             {  
  77.                 arrColWidth[count] = Encoding.GetEncoding(936).GetBytes(item.Value).Length;  
  78.                 count++;  
  79.             }          
  80.   
  81.             int rowIndex = 0;  
  82.   
  83.             foreach (TModel row in list)  
  84.             {  
  85.                 #region 新建表,填充表头,填充列头,样式  
  86.                 if (rowIndex == 65535 || rowIndex == 0)  
  87.                 {  
  88.                     if (rowIndex != 0)  
  89.                     {  
  90.                         sheet = (HSSFSheet)workbook.CreateSheet();  
  91.                     }  
  92.  
  93.                     #region 表头及样式                     
  94.                     AddFirstRow(workbook, sheet, FieldNames, strHeaderText);  
  95.                     #endregion  
  96.                     #region 列头及样式                      
  97.                     AddSecondRow(workbook, sheet, FieldNames, arrColWidth);  
  98.                     #endregion  
  99.                     rowIndex = 2;  
  100.                 }  
  101.                 #endregion  
  102.  
  103.  
  104.                 #region 填充内容  
  105.                 HSSFRow dataRow = (HSSFRow)sheet.CreateRow(rowIndex);  
  106.                 count = 0;  
  107.                 foreach (KeyValuePair<stringstring> column in FieldNames)  
  108.                 {  
  109.                     HSSFCell newCell = (HSSFCell)dataRow.CreateCell(count);  
  110.                     PropertyInfo pinfo = typeof(TModel).GetProperty(column.Key);  
  111.                     string drValue = "";  
  112.                     string dateytype=  "";  
  113.                     if (pinfo != null)   
  114.                     {  
  115.                         drValue = pinfo.GetValue(row, null) == null ? "" : pinfo.GetValue(row, null).ToString();  
  116.                         dateytype = pinfo.PropertyType.ToString();                      
  117.                     }  
  118.                     
  119.                     switch (dateytype){  
  120.                       
  121.                         case "System.String"://字符串类型     
  122.                             newCell.SetCellValue(drValue);  
  123.                             break;  
  124.                         case "System.DateTime"://日期类型     
  125.                             DateTime dateV;  
  126.                             DateTime.TryParse(drValue, out dateV);  
  127.                             newCell.SetCellValue(dateV);  
  128.                             newCell.CellStyle = dateStyle;//格式化显示     
  129.                             break;  
  130.                         case "System.Boolean"://布尔型     
  131.                             bool boolV = false;  
  132.                             bool.TryParse(drValue, out boolV);  
  133.                             newCell.SetCellValue(boolV);  
  134.                             break;  
  135.                         case "System.Int16"://整型     
  136.                         case "System.Int32":  
  137.                         case "System.Int64":  
  138.                         case "System.Byte":  
  139.                             int intV = 0;  
  140.                             int.TryParse(drValue, out intV);  
  141.                             newCell.SetCellValue(intV);  
  142.                             break;  
  143.                         case "System.Decimal"://浮点型     
  144.                         case "System.Double":  
  145.                         case "System.Single":  
  146.                             double doubV = 0;  
  147.                             double.TryParse(drValue, out doubV);  
  148.                             newCell.SetCellValue(doubV);  
  149.                             break;  
  150.                         case "System.DBNull"://空值处理     
  151.                             newCell.SetCellValue("");  
  152.                             break;  
  153.                         default:  
  154.                             newCell.SetCellValue(drValue);  
  155.                             break;  
  156.                     }  
  157.                     count++;  
  158.                 }  
  159.                 #endregion  
  160.   
  161.                 rowIndex++;  
  162.             }  
  163.   
  164.   
  165.             using (MemoryStream ms = new MemoryStream())  
  166.             {  
  167.                 workbook.Write(ms);  
  168.                 ms.Flush();  
  169.                 ms.Position = 0;  
  170.                 sheet.Dispose();  
  171.                 //workbook.Dispose();//一般只用写这一个就OK了,他会遍历并释放所有资源,但当前版本有问题所以只释放sheet     
  172.                 return ms;  
  173.             }  
  174.         }    
  175.          
  176.   
  177.         private static void AddFirstRow(HSSFWorkbook workbook, HSSFSheet sheet, Dictionary<stringstring> FieldNames, string strHeaderText)  
  178.         {  
  179.             HSSFRow headerRow = (HSSFRow)sheet.CreateRow(0);  
  180.             headerRow.HeightInPoints = 25;  
  181.             headerRow.CreateCell(0).SetCellValue(strHeaderText);  
  182.   
  183.             HSSFCellStyle headStyle = (HSSFCellStyle)workbook.CreateCellStyle();  
  184.             headStyle.Alignment = HorizontalAlignment.CENTER;  
  185.             HSSFFont font = (HSSFFont)workbook.CreateFont();  
  186.             font.FontHeightInPoints = 20;  
  187.             font.Boldweight = 700;  
  188.             headStyle.SetFont(font);  
  189.             headerRow.GetCell(0).CellStyle = headStyle;  
  190.             sheet.AddMergedRegion(new Region(0, 0, 0, FieldNames.Count - 1));  
  191.         }  
  192.         private static void AddSecondRow(HSSFWorkbook workbook, HSSFSheet sheet, Dictionary<stringstring> FieldNames, int[] arrColWidth)  
  193.         {  
  194.   
  195.             HSSFRow headerRow = (HSSFRow)sheet.CreateRow(1);  
  196.             HSSFCellStyle headStyle = (HSSFCellStyle)workbook.CreateCellStyle();  
  197.             headStyle.Alignment = HorizontalAlignment.CENTER;  
  198.             HSSFFont font = (HSSFFont)workbook.CreateFont();  
  199.             font.FontHeightInPoints = 10;  
  200.             font.Boldweight = 700;  
  201.             headStyle.SetFont(font);  
  202.             int count = 0; ;  
  203.             foreach (KeyValuePair<stringstring> item in FieldNames)  
  204.             {  
  205.                 //  arrColWidth[count] = Encoding.GetEncoding(936).GetBytes(item.Value).Length;  
  206.                 headerRow.CreateCell(count).SetCellValue(item.Value);  
  207.                 headerRow.GetCell(count).CellStyle = headStyle;  
  208.                 //设置列宽     
  209.                 sheet.SetColumnWidth(count, (arrColWidth[count] + 1) * 256);  
  210.                 count++;  
  211.             }  
  212.         }  
  213.           
  214.         
  215.     }  

阅读(606) | 评论(0) | 转发(0) |
0

上一篇: JS判断 不能为空

下一篇:AtomicBoolean介绍

给主人留下些什么吧!~~