Excel操作

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Data;  
  4. using System.IO;  
  5. using System.Text;  
  6. using System.Web;  
  7. using NPOI;  
  8. using NPOI.HPSF;  
  9. using NPOI.HSSF;  
  10. using NPOI.HSSF.UserModel;  
  11. using NPOI.HSSF.Util;  
  12. using NPOI.POIFS;  
  13. using NPOI.Util;  
  14. using NPOI.SS.UserModel;  
  15. using NPOI.SS.Util;  
  16.   
  17. namespace XXXX.Common  
  18. {  
  19.     /// <summary>  
  20.     /// Excel操作  
  21.     /// </summary>  
  22.     public class ExcelHelper  
  23.     {  
  24.         /// <summary>    
  25.         /// DataTable导出到Excel的MemoryStream    
  26.         /// </summary>    
  27.         /// <param name="dtSource">源DataTable</param>    
  28.         /// <param name="strHeaderText">表头文本</param>    
  29.         public static MemoryStream GetExcelStream(DataTable dtSource, string strHeaderText)  
  30.         {  
  31.             HSSFWorkbook workbook = new HSSFWorkbook();  
  32.             ISheet sheet = workbook.CreateSheet();  
  33.  
  34.             #region 右击文件 属性信息  
  35.             {  
  36.                 DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();  
  37.                 dsi.Company = "";  
  38.                 workbook.DocumentSummaryInformation = dsi;  
  39.   
  40.                 SummaryInformation si = PropertySetFactory.CreateSummaryInformation();  
  41.                 si.Author = ""//填加xls文件作者信息    
  42.                 si.ApplicationName = ""//填加xls文件创建程序信息    
  43.                 si.LastAuthor = ""//填加xls文件最后保存者信息    
  44.                 si.Comments = ""//填加xls文件作者信息    
  45.                 si.Title = ""//填加xls文件标题信息    
  46.                 si.Subject = "";//填加文件主题信息    
  47.                 si.CreateDateTime = DateTime.Now;  
  48.                 workbook.SummaryInformation = si;  
  49.             }  
  50.             #endregion  
  51.   
  52.             ICellStyle dateStyle = workbook.CreateCellStyle();  
  53.             IDataFormat format = workbook.CreateDataFormat();  
  54.             dateStyle.DataFormat = format.GetFormat("yyyy-mm-dd");  
  55.   
  56.             //取得列宽    
  57.             int[] arrColWidth = new int[dtSource.Columns.Count];  
  58.             foreach(DataColumn item in dtSource.Columns)  
  59.             {  
  60.                 arrColWidth[item.Ordinal] = Encoding.GetEncoding(936).GetBytes(item.ColumnName.ToString()).Length;  
  61.             }  
  62.             for(int i = 0; i < dtSource.Rows.Count; i++)  
  63.             {  
  64.                 for(int j = 0; j < dtSource.Columns.Count; j++)  
  65.                 {  
  66.                     int intTemp = Encoding.GetEncoding(936).GetBytes(dtSource.Rows[i][j].ToString()).Length;  
  67.                     if(intTemp > arrColWidth[j])  
  68.                     {  
  69.                         arrColWidth[j] = intTemp;  
  70.                     }  
  71.                 }  
  72.             }  
  73.   
  74.   
  75.   
  76.             int rowIndex = 0;  
  77.   
  78.             foreach(DataRow row in dtSource.Rows)  
  79.             {  
  80.                 #region 新建表,填充表头,填充列头,样式  
  81.                 if(rowIndex == 65535 || rowIndex == 0)  
  82.                 {  
  83.                     if(rowIndex != 0)  
  84.                     {  
  85.                         sheet = workbook.CreateSheet();  
  86.                     }  
  87.  
  88.                     #region 表头及样式  
  89.                     if (!string.IsNullOrEmpty(strHeaderText))  
  90.                     {  
  91.                         IRow headerRow = sheet.CreateRow(0);  
  92.                         headerRow.HeightInPoints = 25;  
  93.                         headerRow.CreateCell(0).SetCellValue(strHeaderText);  
  94.   
  95.                         ICellStyle headStyle = workbook.CreateCellStyle();  
  96.                         headStyle.Alignment = HorizontalAlignment.CENTER;  
  97.                         IFont font = workbook.CreateFont();  
  98.                         font.FontHeightInPoints = 20;  
  99.                         font.Boldweight = 700;  
  100.                         headStyle.SetFont(font);  
  101.   
  102.                         headerRow.GetCell(0).CellStyle = headStyle;  
  103.                         sheet.AddMergedRegion(new CellRangeAddress(0, 0, 0, dtSource.Columns.Count - 1));  
  104.   
  105.                     }  
  106.                     #endregion  
  107.  
  108.  
  109.                     #region 列头及样式  
  110.                     {  
  111.                         IRow headerRow = sheet.CreateRow(1);  
  112.   
  113.   
  114.                         ICellStyle headStyle = workbook.CreateCellStyle();  
  115.                         headStyle.Alignment = HorizontalAlignment.CENTER;  
  116.                         IFont font = workbook.CreateFont();  
  117.                         font.FontHeightInPoints = 10;  
  118.                         font.Boldweight = 700;  
  119.                         headStyle.SetFont(font);  
  120.   
  121.   
  122.                         foreach(DataColumn column in dtSource.Columns)  
  123.                         {  
  124.                             headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);  
  125.                             headerRow.GetCell(column.Ordinal).CellStyle = headStyle;  
  126.   
  127.                             //设置列宽    
  128.                             sheet.SetColumnWidth(column.Ordinal, (arrColWidth[column.Ordinal] + 1) * 256);  
  129.   
  130.                         }  
  131.   
  132.                     }  
  133.                     #endregion  
  134.   
  135.                     rowIndex = 2;  
  136.                 }  
  137.                 #endregion  
  138.  
  139.  
  140.                 #region 填充内容  
  141.                 IRow dataRow = sheet.CreateRow(rowIndex);  
  142.                 foreach(DataColumn column in dtSource.Columns)  
  143.                 {  
  144.                     ICell newCell = dataRow.CreateCell(column.Ordinal);  
  145.   
  146.                     string drValue = row[column].ToString();  
  147.   
  148.                     switch(column.DataType.ToString())  
  149.                     {  
  150.                         case "System.String"://字符串类型    
  151.                             newCell.SetCellValue(drValue);  
  152.                             break;  
  153.                         case "System.DateTime"://日期类型    
  154.                             DateTime dateV;  
  155.                             DateTime.TryParse(drValue, out dateV);  
  156.                             newCell.SetCellValue(dateV);  
  157.   
  158.                             newCell.CellStyle = dateStyle;//格式化显示    
  159.                             break;  
  160.                         case "System.Boolean"://布尔型    
  161.                             bool boolV = false;  
  162.                             bool.TryParse(drValue, out boolV);  
  163.                             newCell.SetCellValue(boolV);  
  164.                             break;  
  165.                         case "System.Int16"://整型    
  166.                         case "System.Int32":  
  167.                         case "System.Int64":  
  168.                         case "System.Byte":  
  169.                             int intV = 0;  
  170.                             int.TryParse(drValue, out intV);  
  171.                             newCell.SetCellValue(intV);  
  172.                             break;  
  173.                         case "System.Decimal"://浮点型    
  174.                         case "System.Double":  
  175.                             double doubV = 0;  
  176.                             double.TryParse(drValue, out doubV);  
  177.                             newCell.SetCellValue(doubV);  
  178.                             break;  
  179.                         case "System.DBNull"://空值处理    
  180.                             newCell.SetCellValue("");  
  181.                             break;  
  182.                         default:  
  183.                             newCell.SetCellValue("");  
  184.                             break;  
  185.                     }  
  186.   
  187.                 }  
  188.                 #endregion  
  189.   
  190.                 rowIndex++;  
  191.             }  
  192.   
  193.   
  194.             using(MemoryStream ms = new MemoryStream())  
  195.             {  
  196.                 workbook.Write(ms);  
  197.                 ms.Flush();  
  198.                 ms.Position = 0;  
  199.   
  200.                 workbook.Dispose();  
  201.                 return ms;  
  202.             }  
  203.   
  204.         }  
  205.   
  206.   
  207.         /// <summary>    
  208.         /// 导出Excel  
  209.         /// </summary>    
  210.         /// <param name="dtSource">源DataTable</param>    
  211.         /// <param name="strHeaderText">表头文本</param>    
  212.         /// <param name="strFileName">文件名</param>    
  213.         public static void Export(DataTable dtSource, string strHeaderText, string strFileName)  
  214.         {  
  215.             HttpContext curContext = HttpContext.Current;  
  216.             // 设置编码和附件格式    
  217.             curContext.Response.ContentType = "application/vnd.ms-excel";  
  218.             curContext.Response.ContentEncoding = Encoding.UTF8;  
  219.             curContext.Response.Charset = "UTF-8";  
  220.   
  221.             if (curContext.Request.ServerVariables["HTTP_USER_AGENT"].IndexOf("Firefox") > -1)  
  222.             {  
  223.                 curContext.Response.AddHeader("Content-Disposition""attachment;FileName=" + strFileName);  
  224.             }  
  225.             else  
  226.             {  
  227.                 curContext.Response.AppendHeader("Content-Disposition""attachment;filename=" + HttpUtility.UrlEncode(strFileName, Encoding.UTF8));   
  228.             }              
  229.             curContext.Response.BinaryWrite(GetExcelStream(dtSource, strHeaderText).GetBuffer());  
  230.             curContext.Response.End();  
  231.         }  
  232.               
  233.         /// <summary>  
  234.         /// 读取excel    
  235.         /// 默认第一行为标头    
  236.         /// </summary>    
  237.         /// <param name="strFileName">excel文档路径</param>    
  238.         /// <returns></returns>    
  239.         public static DataTable Import(string strFileName)  
  240.         {  
  241.             DataTable dt = new DataTable();  
  242.   
  243.             HSSFWorkbook hssfworkbook;  
  244.             using(FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read))  
  245.             {  
  246.                 hssfworkbook = new HSSFWorkbook(file);  
  247.             }  
  248.             ISheet sheet = hssfworkbook.GetSheetAt(0);  
  249.             System.Collections.IEnumerator rows = sheet.GetRowEnumerator();  
  250.   
  251.             IRow headerRow = sheet.GetRow(0);  
  252.             int cellCount = headerRow.LastCellNum;  
  253.   
  254.             for(int j = 0; j < cellCount; j++)  
  255.             {  
  256.                 ICell cell = headerRow.GetCell(j);  
  257.                 dt.Columns.Add(cell.ToString());  
  258.             }  
  259.   
  260.             for(int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++)  
  261.             {  
  262.                 IRow row = sheet.GetRow(i);  
  263.                 DataRow dataRow = dt.NewRow();  
  264.   
  265.                 for(int j = row.FirstCellNum; j < cellCount; j++)  
  266.                 {  
  267.                     if(row.GetCell(j) != null)  
  268.                         dataRow[j] = row.GetCell(j).ToString();  
  269.                 }  
  270.   
  271.                 dt.Rows.Add(dataRow);  
  272.             }  
  273.             return dt;  
  274.         }  
  275.   
  276.   
  277.     }  
  278. }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值