[C#] NPOI导出与读取Excel →→→→→进入此内容的聊天室

来自 , 2019-11-09, 写在 C#, 查看 146 次.
URL http://www.code666.cn/view/7876acb6
  1. using System;
  2.  
  3.  
  4. using System.Collections.Generic;
  5.  
  6. using System.Linq;
  7.  
  8. using System.Text;
  9.  
  10. using System.Data;
  11.  
  12. using System.IO;
  13.  
  14. using NPOI;
  15.  
  16. using NPOI.HPSF;
  17.  
  18. using NPOI.HSSF;
  19.  
  20. using NPOI.HSSF.UserModel;
  21.  
  22. using NPOI.HSSF.Util;
  23.  
  24. using NPOI.POIFS;
  25.  
  26. using NPOI.Util;  
  27.  
  28.  
  29.  
  30.  
  31. namespace ConsoleApplication2
  32.  
  33. {
  34.  
  35.     internal class Program
  36.  
  37.     {
  38.  
  39.         private static void Main(string[] args)
  40.  
  41.         {
  42.  
  43.             DataTable newdtb = new DataTable();
  44.  
  45.             newdtb.Columns.Add("Id", typeof (int));
  46.  
  47.             newdtb.Columns.Add("ProName", typeof (string));
  48.  
  49.             newdtb.Columns.Add("ProPrice", typeof (decimal));
  50.  
  51.             newdtb.Columns["Id"].AutoIncrement = true;
  52.  
  53.  
  54.  
  55.  
  56.             for (int i = 1; i < 11; i++)
  57.  
  58.             {
  59.  
  60.                 DataRow newRow = newdtb.NewRow();
  61.  
  62.                 newRow["ProCardNo"] = "12312345612543256" + i.ToString();
  63.  
  64.                 newRow["ProPrice"] = 12.3m;
  65.  
  66.                 newdtb.Rows.Add(newRow);
  67.  
  68.             }
  69.  
  70.             DataTable dt = newdtb;
  71.  
  72.            
  73.  
  74.  
  75.                 Export(dt, "aaa", "d:\\222.xls");
  76.  
  77.  
  78.  
  79.  
  80.         }
  81.  
  82.  
  83.  
  84.  
  85.  
  86.         #region  NPOI导出到Excel
  87.  
  88.  
  89.  
  90.  
  91.         /// <summary>
  92.  
  93.         /// DataTable导出到Excel文件
  94.  
  95.         /// </summary>
  96.  
  97.         /// <param name="dtSource">源DataTable</param>
  98.  
  99.         /// <param name="strHeaderText">表头文本</param>
  100.  
  101.         /// <param name="strFileName">保存位置</param>
  102.  
  103.         public static void Export(DataTable dtSource, string strHeaderText, string strFileName)
  104.  
  105.         {
  106.  
  107.             using (MemoryStream ms = Export(dtSource, strHeaderText))
  108.  
  109.             {
  110.  
  111.                 using (FileStream fs = new FileStream(strFileName, FileMode.Create, FileAccess.Write))
  112.  
  113.                 {
  114.  
  115.                     byte[] data = ms.ToArray();
  116.  
  117.                     fs.Write(data, 0, data.Length);
  118.  
  119.                     fs.Flush();
  120.  
  121.                 }
  122.  
  123.             }
  124.  
  125.         }
  126.  
  127.  
  128.  
  129.         /// <summary>
  130.  
  131.         /// DataTable导出到Excel的MemoryStream
  132.  
  133.         /// </summary>
  134.  
  135.         /// <param name="dtSource">源DataTable</param>
  136.  
  137.         /// <param name="strHeaderText">表头文本</param>
  138.  
  139.         public static MemoryStream Export(DataTable dtSource, string strHeaderText)
  140.  
  141.         {
  142.  
  143.             HSSFWorkbook workbook = new HSSFWorkbook();
  144.  
  145.             HSSFSheet sheet = workbook.CreateSheet();
  146.  
  147.  
  148.  
  149.             #region 右击文件 属性信息
  150.  
  151.  
  152.             {
  153.  
  154.                 DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
  155.  
  156.                 dsi.Company = "NPOI";
  157.  
  158.                 workbook.DocumentSummaryInformation = dsi;
  159.  
  160.  
  161.                 SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
  162.  
  163.                 si.Author = "文件作者信息"; //填加xls文件作者信息
  164.  
  165.                 si.ApplicationName = "创建程序信息"; //填加xls文件创建程序信息
  166.  
  167.                 si.LastAuthor = "最后保存者信息"; //填加xls文件最后保存者信息
  168.  
  169.                 si.Comments = "作者信息"; //填加xls文件作者信息
  170.  
  171.                 si.Title = "标题信息"; //填加xls文件标题信息
  172.  
  173.                 si.Subject = "主题信息"; //填加文件主题信息
  174.  
  175.                 si.CreateDateTime = DateTime.Now;
  176.  
  177.                 workbook.SummaryInformation = si;
  178.  
  179.             }
  180.  
  181.  
  182.             #endregion
  183.  
  184.  
  185.             HSSFCellStyle dateStyle = workbook.CreateCellStyle();
  186.  
  187.             HSSFDataFormat format = workbook.CreateDataFormat();
  188.  
  189.             dateStyle.DataFormat = format.GetFormat("yyyy-mm-dd");
  190.  
  191.  
  192.             //取得列宽
  193.  
  194.             int[] arrColWidth = new int[dtSource.Columns.Count];
  195.  
  196.             foreach (DataColumn item in dtSource.Columns)
  197.  
  198.             {
  199.  
  200.                 arrColWidth[item.Ordinal] = Encoding.GetEncoding(936).GetBytes(item.ColumnName.ToString()).Length;
  201.  
  202.             }
  203.  
  204.             for (int i = 0; i < dtSource.Rows.Count; i++)
  205.  
  206.             {
  207.  
  208.                 for (int j = 0; j < dtSource.Columns.Count; j++)
  209.  
  210.                 {
  211.  
  212.                     int intTemp = Encoding.GetEncoding(936).GetBytes(dtSource.Rows[i][j].ToString()).Length;
  213.  
  214.                     if (intTemp > arrColWidth[j])
  215.  
  216.                     {
  217.  
  218.                         arrColWidth[j] = intTemp;
  219.  
  220.                     }
  221.  
  222.                 }
  223.  
  224.             }
  225.  
  226.             int rowIndex = 0;
  227.  
  228.             foreach (DataRow row in dtSource.Rows)
  229.  
  230.             {
  231.  
  232.                 #region 新建表,填充表头,填充列头,样式
  233.  
  234.  
  235.                 if (rowIndex == 65535 || rowIndex == 0)
  236.  
  237.                 {
  238.  
  239.                     if (rowIndex != 0)
  240.  
  241.                     {
  242.  
  243.                         sheet = workbook.CreateSheet();
  244.  
  245.                     }
  246.  
  247.                     #region 表头及样式
  248.  
  249.                     {
  250.  
  251.                         HSSFRow headerRow = sheet.CreateRow(0);
  252.  
  253.                         headerRow.HeightInPoints = 25;
  254.  
  255.                         headerRow.CreateCell(0).SetCellValue(strHeaderText);
  256.  
  257.  
  258.  
  259.  
  260.                         HSSFCellStyle headStyle = workbook.CreateCellStyle();
  261.  
  262.                         headStyle.Alignment = CellHorizontalAlignment.CENTER;
  263.  
  264.                         HSSFFont font = workbook.CreateFont();
  265.  
  266.                         font.FontHeightInPoints = 20;
  267.  
  268.                         font.Boldweight = 700;
  269.  
  270.                         headStyle.SetFont(font);
  271.  
  272.                         headerRow.GetCell(0).CellStyle = headStyle;
  273.  
  274.                         sheet.AddMergedRegion(new Region(0, 0, 0, dtSource.Columns.Count - 1));
  275.  
  276.                         headerRow.Dispose();
  277.  
  278.                     }
  279.  
  280.  
  281.  
  282.  
  283.                     #endregion
  284.  
  285.  
  286.  
  287.  
  288.  
  289.  
  290.  
  291.                     #region 列头及样式
  292.  
  293.  
  294.  
  295.  
  296.                     {
  297.  
  298.                         HSSFRow headerRow = sheet.CreateRow(1);
  299.  
  300.                         HSSFCellStyle headStyle = workbook.CreateCellStyle();
  301.  
  302.                         headStyle.Alignment = CellHorizontalAlignment.CENTER;
  303.  
  304.                         HSSFFont font = workbook.CreateFont();
  305.  
  306.                         font.FontHeightInPoints = 10;
  307.  
  308.                         font.Boldweight = 700;
  309.  
  310.                         headStyle.SetFont(font);
  311.  
  312.                         foreach (DataColumn column in dtSource.Columns)
  313.  
  314.                         {
  315.  
  316.                             headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);
  317.  
  318.                             headerRow.GetCell(column.Ordinal).CellStyle = headStyle;
  319.  
  320.  
  321.  
  322.  
  323.                             //设置列宽
  324.  
  325.                             sheet.SetColumnWidth(column.Ordinal, (arrColWidth[column.Ordinal] + 1)*256);
  326.  
  327.                         }
  328.  
  329.                         headerRow.Dispose();
  330.  
  331.                     }
  332.  
  333.  
  334.  
  335.  
  336.                     #endregion
  337.  
  338.  
  339.  
  340.  
  341.                     rowIndex = 2;
  342.  
  343.                 }
  344.  
  345.  
  346.  
  347.  
  348.                 #endregion
  349.  
  350.  
  351.  
  352.  
  353.  
  354.  
  355.  
  356.                 #region 填充内容
  357.  
  358.  
  359.  
  360.  
  361.                 HSSFRow dataRow = sheet.CreateRow(rowIndex);
  362.  
  363.                 foreach (DataColumn column in dtSource.Columns)
  364.  
  365.                 {
  366.  
  367.                     HSSFCell newCell = dataRow.CreateCell(column.Ordinal);
  368.  
  369.  
  370.  
  371.  
  372.                     string drValue = row[column].ToString();
  373.  
  374.  
  375.  
  376.  
  377.                     switch (column.DataType.ToString())
  378.  
  379.                     {
  380.  
  381.                         case "System.String": //字符串类型
  382.  
  383.                             newCell.SetCellValue(drValue);
  384.  
  385.                             break;
  386.  
  387.                         case "System.DateTime": //日期类型
  388.  
  389.                             DateTime dateV;
  390.  
  391.                             DateTime.TryParse(drValue, out dateV);
  392.  
  393.                             newCell.SetCellValue(dateV);
  394.  
  395.  
  396.  
  397.  
  398.                             newCell.CellStyle = dateStyle; //格式化显示
  399.  
  400.                             break;
  401.  
  402.                         case "System.Boolean": //布尔型
  403.  
  404.                             bool boolV = false;
  405.  
  406.                             bool.TryParse(drValue, out boolV);
  407.  
  408.                             newCell.SetCellValue(boolV);
  409.  
  410.                             break;
  411.  
  412.                         case "System.Int16": //整型
  413.  
  414.                         case "System.Int32":
  415.  
  416.                         case "System.Int64":
  417.  
  418.                         case "System.Byte":
  419.  
  420.                             int intV = 0;
  421.  
  422.                             int.TryParse(drValue, out intV);
  423.  
  424.                             newCell.SetCellValue(intV);
  425.  
  426.                             break;
  427.  
  428.                         case "System.Decimal": //浮点型
  429.  
  430.                         case "System.Double":
  431.  
  432.                             double doubV = 0;
  433.  
  434.                             double.TryParse(drValue, out doubV);
  435.  
  436.                             newCell.SetCellValue(doubV);
  437.  
  438.                             break;
  439.  
  440.                         case "System.DBNull": //空值处理
  441.  
  442.                             newCell.SetCellValue("");
  443.  
  444.                             break;
  445.  
  446.                         default:
  447.  
  448.                             newCell.SetCellValue("");
  449.  
  450.                             break;
  451.  
  452.                     }
  453.  
  454.  
  455.  
  456.  
  457.                 }
  458.  
  459.  
  460.  
  461.  
  462.                 #endregion
  463.  
  464.  
  465.  
  466.  
  467.                 rowIndex++;
  468.  
  469.             }
  470.  
  471.             using (MemoryStream ms = new MemoryStream())
  472.  
  473.             {
  474.  
  475.                 workbook.Write(ms);
  476.  
  477.                 ms.Flush();
  478.  
  479.                 ms.Position = 0;
  480.  
  481.  
  482.  
  483.  
  484.                 sheet.Dispose();
  485.  
  486.                 //workbook.Dispose();//一般只用写这一个就OK了,他会遍历并释放所有资源,但当前版本有问题所以只释放sheet
  487.  
  488.                 return ms;
  489.  
  490.             }
  491.  
  492.         }
  493.  
  494.  
  495.  
  496.  
  497.         #endregion
  498.  
  499.  
  500.  
  501.  
  502.         #region  Excl读取
  503.  
  504.         /// <summary>
  505.  
  506.         /// 默认第一行为标头
  507.  
  508.         /// </summary>
  509.  
  510.         /// <param name="strFileName">excel文档路径</param>
  511.  
  512.         /// <returns></returns>
  513.  
  514.         public static DataTable Import(string strFileName)
  515.  
  516.         {
  517.  
  518.             DataTable dt = new DataTable();
  519.  
  520.  
  521.  
  522.  
  523.             HSSFWorkbook hssfworkbook;
  524.  
  525.             using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read))
  526.  
  527.             {
  528.  
  529.                 hssfworkbook = new HSSFWorkbook(file);
  530.  
  531.             }
  532.  
  533.             HSSFSheet sheet = hssfworkbook.GetSheetAt(0);
  534.  
  535.             System.Collections.IEnumerator rows = sheet.GetRowEnumerator();
  536.  
  537.  
  538.  
  539.  
  540.             HSSFRow headerRow = sheet.GetRow(0);
  541.  
  542.             int cellCount = headerRow.LastCellNum;
  543.  
  544.  
  545.  
  546.  
  547.             for (int j = 0; j < cellCount; j++)
  548.  
  549.             {
  550.  
  551.                 HSSFCell cell = headerRow.GetCell(j);
  552.  
  553.                 dt.Columns.Add(cell.ToString());
  554.  
  555.             }
  556.  
  557.  
  558.  
  559.  
  560.             for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++)
  561.  
  562.             {
  563.  
  564.                 HSSFRow row = sheet.GetRow(i);
  565.  
  566.                 DataRow dataRow = dt.NewRow();
  567.  
  568.  
  569.  
  570.  
  571.                 for (int j = row.FirstCellNum; j < cellCount; j++)
  572.  
  573.                 {
  574.  
  575.                     if (row.GetCell(j) != null)
  576.  
  577.                         dataRow[j] = row.GetCell(j).ToString();
  578.  
  579.                 }
  580.  
  581.  
  582.  
  583.  
  584.                 dt.Rows.Add(dataRow);
  585.  
  586.             }
  587.  
  588.             return dt;
  589.  
  590.         }
  591.  
  592.  
  593.  
  594.  
  595.         #endregion
  596.  
  597.     }
  598.  
  599. }

回复 "NPOI导出与读取Excel"

这儿你可以回复上面这条便签

captcha