利用NPOI开源的读写Excel、WORD等微软OLE2组件读写execl,控制样式或单元格

[csharp]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.UI;  
  6. using System.Web.UI.WebControls;  
  7. //add  
  8. using System.Data;  
  9. using System.IO;  
  10. using NPOI;  
  11. using NPOI.HSSF.UserModel;  
  12.   
  13.   
  14. public partial class ExeclOperation : System.Web.UI.Page  
  15. {  
  16.     #region 页面加载  
  17.     protected void Page_Load(object sender, EventArgs e)  
  18.     {  
  19.         DataTable dt = ReadExcelToDataTable("~/xls/demo001.xls", 0, 0);  
  20.         ViewState["dtview"] = dt;  
  21.         GridView1.DataSource = dt;  
  22.         GridView1.DataBind();  
  23.     }  
  24.     #endregion   
  25.  
  26.     #region DS直接生成Execl  
  27.     protected void btnExport_Click(object sender, EventArgs e)  
  28.     {  
  29.         DataSet ds = new DataSet();  
  30.         DataTable dt = ViewState["dtview"as DataTable;  
  31.         ds.Tables.Add(dt);  
  32.         bool success = ExportExcelByDataSet(ds, "~/xls/""demo.xls""这是测试数据");  
  33.         if (success)  
  34.         {  
  35.             ScriptManager.RegisterClientScriptBlock(Page, typeof(Page), "alert1""alert('生成execl文件成功')"true);  
  36.         }  
  37.         else  
  38.         {  
  39.             ScriptManager.RegisterClientScriptBlock(Page, typeof(Page), "alert2""alert('生成execl文件失败')"true);  
  40.         }  
  41.     }  
  42.     #endregion   
  43.  
  44.     #region GridView自动列适应,不换行  
  45.     protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)  
  46.     {  
  47.         if (e.Row.RowType == DataControlRowType.DataRow || e.Row.RowType == DataControlRowType.Header)  
  48.         {  
  49.             TableCellCollection cells1 = e.Row.Cells;  
  50.             for (int i = 0; i < cells1.Count; i++)  
  51.             {  
  52.                 cells1[i].Wrap = false;  
  53.             }  
  54.         }  
  55.     }   
  56.     #endregion   
  57.  
  58.     #region DataSet与Execl互转  
  59.     /// <summary>  
  60.     /// 传入ds直接生成excel文件  
  61.     /// </summary>  
  62.     /// <param name="ds">DataSet</param>  
  63.     /// <param name="strPath">文件路径</param>  
  64.     /// <param name="strFileName">文件名</param>  
  65.     /// <param name="ReportHeader">execl表头</param>  
  66.     /// <returns></returns>  
  67.     public static bool ExportExcelByDataSet(DataSet ds, string strPath, string strFileName, string ReportHeader = "")  
  68.     {  
  69.         //NPOI   
  70.         HSSFWorkbook hssfworkbook2 = new HSSFWorkbook();  
  71.         HSSFSheet sheet = (HSSFSheet)hssfworkbook2.CreateSheet("sheet1");  
  72.         //定义字体 font   设置字体类型和大小  
  73.         HSSFFont font = (HSSFFont)hssfworkbook2.CreateFont();  
  74.         font.FontName = "宋体";  
  75.         font.FontHeightInPoints = 11;  
  76.   
  77.         //定义单元格格式;单元格格式style1 为font的格式  
  78.         HSSFCellStyle style1 = (HSSFCellStyle)hssfworkbook2.CreateCellStyle();  
  79.         style1.SetFont(font);  
  80.         style1.Alignment = NPOI.SS.UserModel.HorizontalAlignment.LEFT;  
  81.   
  82.         HSSFCellStyle style2 = (HSSFCellStyle)hssfworkbook2.CreateCellStyle();  
  83.         style2.SetFont(font);  
  84.         style2.Alignment = NPOI.SS.UserModel.HorizontalAlignment.CENTER;  
  85.         style2.BorderBottom = NPOI.SS.UserModel.BorderStyle.THIN;  
  86.         style2.BorderLeft = NPOI.SS.UserModel.BorderStyle.THIN;  
  87.         style2.BorderRight = NPOI.SS.UserModel.BorderStyle.THIN;  
  88.         style2.BorderTop = NPOI.SS.UserModel.BorderStyle.THIN;  
  89.         //style2.WrapText = true;  
  90.   
  91.         //设置大标题行  
  92.         int RowCount = 0;  
  93.         int arrFlag = 0;  
  94.         string TileName1 = "";  
  95.         string TileName2 = "";  
  96.   
  97.         string s = ReportHeader;  
  98.         string[] sArray = s.Split('|');  
  99.         if (ReportHeader != "")  
  100.         {  
  101.             foreach (string i in sArray)  
  102.             {  
  103.                 string str1 = i.ToString();  
  104.                 string[] subArray = str1.Split('@');  
  105.                 foreach (string k in subArray)  
  106.                 {  
  107.                     Console.WriteLine(k.ToString());  
  108.                     if (arrFlag == 0)  
  109.                     {  
  110.                         TileName1 = k.ToString();  
  111.                     }  
  112.                     else  
  113.                     {  
  114.                         TileName2 = k.ToString();  
  115.                     }  
  116.                     arrFlag = arrFlag + 1;  
  117.                 }  
  118.                 HSSFRow row0 = (HSSFRow)sheet.CreateRow(RowCount); //创建报表表头标题  8列  
  119.                 row0.CreateCell(0).SetCellValue(TileName1);  
  120.                 row0.CreateCell(1).SetCellValue(TileName2);  
  121.                 RowCount = RowCount + 1;  
  122.                 arrFlag = 0;  
  123.             }  
  124.         }  
  125.         //设置全局列宽和行高  
  126.         sheet.DefaultColumnWidth = 14;//全局列宽  
  127.         sheet.DefaultRowHeightInPoints = 15;//全局行高  
  128.         //设置标题行数据  
  129.         int a = 0;  
  130.         string mColumnName = "";  
  131.   
  132.         HSSFRow row1 = (HSSFRow)sheet.CreateRow(RowCount); //创建报表表头标题  8列  
  133.         for (int k = 0; k < ds.Tables[0].Columns.Count; k++)  
  134.         {  
  135.   
  136.             mColumnName = ds.Tables[0].Columns[k].ColumnName.ToString();  
  137.             row1.CreateCell(a).SetCellValue(mColumnName);  
  138.             row1.Cells[a].CellStyle = style2;  
  139.             a++;  
  140.   
  141.         }  
  142.         //填写ds数据进excel  
  143.         for (int i = 0; i < ds.Tables[0].Rows.Count; i++)//写6行数据  
  144.         {  
  145.             HSSFRow row2 = (HSSFRow)sheet.CreateRow(i + RowCount + 1);  
  146.             int b = 0;  
  147.             for (int j = 0; j < ds.Tables[0].Columns.Count; j++)  
  148.             {  
  149.                 string DgvValue = "";  
  150.                 DgvValue = ds.Tables[0].Rows[i][j].ToString(); ;  
  151.                 row2.CreateCell(b).SetCellValue(DgvValue);  
  152.                 b++;  
  153.             }  
  154.         }  
  155.         //获取用户选择路径  
  156.         string ReportPath = HttpContext.Current.Server.MapPath(strPath + strFileName);  
  157.   
  158.         //创建excel  
  159.         System.IO.FileStream file3 = new FileStream(ReportPath, FileMode.Create);  
  160.         hssfworkbook2.Write(file3);  
  161.         file3.Close();  
  162.         return true;  
  163.     }  
  164.   
  165.     /// <summary>  
  166.     /// 用NPOI直接读取excel返回DataTable  
  167.     /// </summary>  
  168.     /// <param name="ExcelFileStream">文件流</param>  
  169.     /// <param name="SheetIndex">Sheet序号</param>  
  170.     /// <param name="StartRowIndex">开始行号</param>  
  171.     /// <returns></returns>  
  172.     public static DataTable ReadExcelToDataTable(Stream ExcelFileStream, int SheetIndex, int StartRowIndex)  
  173.     {  
  174.         HSSFWorkbook workbook = new HSSFWorkbook(ExcelFileStream);  
  175.         HSSFSheet sheet = (HSSFSheet)workbook.GetSheetAt(SheetIndex);  
  176.   
  177.         DataTable table = new DataTable();  
  178.         HSSFRow headerRow = (HSSFRow)sheet.GetRow(StartRowIndex);  
  179.         int cellCount = headerRow.LastCellNum;  
  180.   
  181.         for (int i = headerRow.FirstCellNum; i < cellCount; i++)  
  182.         {  
  183.             DataColumn column = new DataColumn(headerRow.GetCell(i).StringCellValue);  
  184.             table.Columns.Add(column);  
  185.         }  
  186.         int rowCount = sheet.LastRowNum;  
  187.         for (int i = (StartRowIndex + 1); i <= sheet.LastRowNum; i++)  
  188.         {  
  189.             HSSFRow row = (HSSFRow)sheet.GetRow(i);  
  190.             DataRow dataRow = table.NewRow();  
  191.             for (int j = row.FirstCellNum; j < cellCount; j++)  
  192.             {  
  193.                 if (row.GetCell(j) != null)  
  194.                     dataRow[j] = row.GetCell(j).ToString();  
  195.             }  
  196.             table.Rows.Add(dataRow);  
  197.         }  
  198.         ExcelFileStream.Close();  
  199.         workbook = null;  
  200.         sheet = null;  
  201.         return table;  
  202.     }  
  203.   
  204.     /// <summary>  
  205.     /// 用NPOI直接读取excel返回DataTable  
  206.     /// </summary>  
  207.     /// <param name="FilePath">文件路径</param>  
  208.     /// <param name="SheetIndex">Sheet序号</param>  
  209.     /// <param name="StartRowIndex">开始行号</param>  
  210.     /// <returns></returns>  
  211.     public static DataTable ReadExcelToDataTable(string FilePath, int SheetIndex, int StartRowIndex)  
  212.     {  
  213.         DataSet ds = new DataSet();  
  214.         FileStream fs = File.Open(HttpContext.Current.Server.MapPath(FilePath), FileMode.Open);  
  215.         DataTable dt = ReadExcelToDataTable(fs, SheetIndex, StartRowIndex);  
  216.         return dt;  
  217.     }  
  218.     #endregion   
  219. }  

 

[csharp]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. #region DataSet与Execl互转  
  2. /// <summary>      
  3. /// 传入ds直接生成excel文件      
  4. /// </summary>      
  5. /// <param name="ds">DataSet</param>      
  6. /// <param name="strPath">文件路径</param>      
  7. /// <param name="ReportHeader">execl表头</param>      
  8. /// <returns></returns>      
  9. public static bool ExportExcelByDataSet(DataSet ds, string strPath, string ReportHeader = "")  
  10. {  
  11.     //NPOI       
  12.     HSSFWorkbook hssfworkbook2 = new HSSFWorkbook();  
  13.     #region 循环开始  
  14.     for (int p = 0; p < ds.Tables.Count; p++)  
  15.     {  
  16.         int t = p + 1;  
  17.         HSSFSheet sheet = (HSSFSheet)hssfworkbook2.CreateSheet("page" + t);  
  18.         //定义字体 font   设置字体类型和大小      
  19.         HSSFFont font = (HSSFFont)hssfworkbook2.CreateFont();  
  20.         font.FontName = "宋体";  
  21.         font.FontHeightInPoints = 11;  
  22.   
  23.         //定义单元格格式;单元格格式style1 为font的格式      
  24.         HSSFCellStyle style1 = (HSSFCellStyle)hssfworkbook2.CreateCellStyle();  
  25.         style1.SetFont(font);  
  26.         style1.Alignment = NPOI.SS.UserModel.HorizontalAlignment.LEFT;  
  27.   
  28.         HSSFCellStyle style2 = (HSSFCellStyle)hssfworkbook2.CreateCellStyle();  
  29.         style2.SetFont(font);  
  30.         style2.Alignment = NPOI.SS.UserModel.HorizontalAlignment.CENTER;  
  31.         style2.BorderBottom = NPOI.SS.UserModel.BorderStyle.THIN;  
  32.         style2.BorderLeft = NPOI.SS.UserModel.BorderStyle.THIN;  
  33.         style2.BorderRight = NPOI.SS.UserModel.BorderStyle.THIN;  
  34.         style2.BorderTop = NPOI.SS.UserModel.BorderStyle.THIN;  
  35.         //style2.WrapText = true;      
  36.   
  37.         //设置大标题行      
  38.         int RowCount = 0;  
  39.         int arrFlag = 0;  
  40.         string TileName1 = "";  
  41.         string TileName2 = "";  
  42.   
  43.         string s = ReportHeader;  
  44.         string[] sArray = s.Split('|');  
  45.         if (ReportHeader != "")  
  46.         {  
  47.             foreach (string i in sArray)  
  48.             {  
  49.                 string str1 = i.ToString();  
  50.                 string[] subArray = str1.Split('@');  
  51.                 foreach (string k in subArray)  
  52.                 {  
  53.                     Console.WriteLine(k.ToString());  
  54.                     if (arrFlag == 0)  
  55.                     {  
  56.                         TileName1 = k.ToString();  
  57.                     }  
  58.                     else  
  59.                     {  
  60.                         TileName2 = k.ToString();  
  61.                     }  
  62.                     arrFlag = arrFlag + 1;  
  63.                 }  
  64.                 HSSFRow row0 = (HSSFRow)sheet.CreateRow(RowCount); //创建报表表头标题  8列      
  65.                 row0.CreateCell(0).SetCellValue(TileName1);  
  66.                 row0.CreateCell(1).SetCellValue(TileName2);  
  67.                 RowCount = RowCount + 1;  
  68.                 arrFlag = 0;  
  69.             }  
  70.         }  
  71.         //设置全局列宽和行高      
  72.         sheet.DefaultColumnWidth = 14;//全局列宽      
  73.         sheet.DefaultRowHeightInPoints = 15;//全局行高      
  74.         //设置标题行数据      
  75.         int a = 0;  
  76.         string mColumnName = "";  
  77.   
  78.         HSSFRow row1 = (HSSFRow)sheet.CreateRow(RowCount); //创建报表表头标题  8列      
  79.         for (int k = 0; k < ds.Tables[p].Columns.Count; k++)  
  80.         {  
  81.   
  82.             mColumnName = ds.Tables[p].Columns[k].ColumnName.ToString();  
  83.             row1.CreateCell(a).SetCellValue(mColumnName);  
  84.             row1.Cells[a].CellStyle = style2;  
  85.             a++;  
  86.   
  87.         }  
  88.         //填写ds数据进excel      
  89.         for (int i = 0; i < ds.Tables[p].Rows.Count; i++)//写6行数据      
  90.         {  
  91.             HSSFRow row2 = (HSSFRow)sheet.CreateRow(i + RowCount + 1);  
  92.             int b = 0;  
  93.             for (int j = 0; j < ds.Tables[p].Columns.Count; j++)  
  94.             {  
  95.                 string DgvValue = "";  
  96.                 DgvValue = ds.Tables[p].Rows[i][j].ToString(); ;  
  97.                 row2.CreateCell(b).SetCellValue(DgvValue);  
  98.                 b++;  
  99.             }  
  100.         }  
  101.     }  
  102.     #endregion  
  103.   
  104.     //获取用户选择路径      
  105.     string ReportPath = (strPath);  
  106.   
  107.     //创建excel      
  108.     System.IO.FileStream file3 = new FileStream(ReportPath, FileMode.Create);  
  109.     hssfworkbook2.Write(file3);  
  110.     file3.Close();  
  111.     return true;  
  112. }  
  113.   
  114. /// <summary>  
  115. /// 用NPOI直接读取excel返回DataSet  
  116. /// </summary>  
  117. /// <param name="ExcelFileStream">FileStream fs = File.Open(dlg.FileName, FileMode.Open);</param>  
  118. /// <param name="SheetCount">sheet数量</param>  
  119. /// <returns></returns>  
  120. public static DataSet ReadExcelToDataSet(Stream ExcelFileStream,int SheetCount)  
  121. {  
  122.     HSSFWorkbook workbook = new HSSFWorkbook(ExcelFileStream);  
  123.     DataSet ds = new DataSet();  
  124.   
  125.     for (int k = 0; k < SheetCount; k++)  
  126.     {  
  127.         HSSFSheet sheet = (HSSFSheet)workbook.GetSheetAt(k);  
  128.         DataTable table = new DataTable("table" + k);  
  129.         HSSFRow headerRow = (HSSFRow)sheet.GetRow(0);  
  130.         int cellCount = headerRow.LastCellNum;  
  131.   
  132.         for (int i = headerRow.FirstCellNum; i < cellCount; i++)  
  133.         {  
  134.             string columnName = headerRow.GetCell(i).StringCellValue;  
  135.             DataColumn column = new DataColumn(columnName);  
  136.             if (!table.Columns.Contains(columnName))  
  137.             {  
  138.                 table.Columns.Add(column);  
  139.             }  
  140.         }  
  141.         int rowCount = sheet.LastRowNum;  
  142.         for (int i = (0 + 1); i <= sheet.LastRowNum; i++)  
  143.         {  
  144.             HSSFRow row = (HSSFRow)sheet.GetRow(i);  
  145.             DataRow dataRow = table.NewRow();  
  146.             for (int j = row.FirstCellNum; j < cellCount; j++)  
  147.             {  
  148.                 if (row.GetCell(j) != null)  
  149.                     dataRow[j] = row.GetCell(j);  
  150.             }  
  151.             table.Rows.Add(dataRow);  
  152.         }  
  153.         sheet = null;  
  154.         ds.Tables.Add(table);  
  155.     }  
  156.     workbook = null;  
  157.     ExcelFileStream.Close();  
  158.   
  159.     return ds;  
  160. }  
  161. #endregion  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值