1. 首先建立一个空白的工作簿用作测试,并在其中建立空白工作表,在表中建立空白行,在行中建立单元格,并填入内容:
  1.  
  1.  
  1. //建立空白工作簿
  2. IWorkbook workbook = new HSSFWorkbook();
  3. //在工作簿中:建立空白工作表
  4. ISheet sheet = workbook.CreateSheet();
  5. //在工作表中:建立行,参数为行号,从0计
  6. IRow row = sheet.CreateRow(0);
  1. //在行中:建立单元格,参数为列号,从0计
  2. ICell cell = row.CreateCell(0);
  3. //设置单元格内容
  4. cell.SetCellValue("实习鉴定表");
  1.  


  1. 设置单元格样式:
    设置单元格样式时需要注意,务必创建一个新的样式对象进行设置,否则会将工作表所有单元格的样式一同设置,它们应该共享的是一个样式对象:
  1.  
  1.  
  1.  
  1. ICellStyle style = workbook.CreateCellStyle();
  2. //设置单元格的样式:水平对齐居中
  3. style.Alignment = HorizontalAlignment.CENTER;
  4. //新建一个字体样式对象
  1. IFont font = workbook.CreateFont();
  2. //设置字体加粗样式
  1. font.Boldweight = short.MaxValue;
  2. //使用SetFont方法将字体样式添加到单元格样式中
  1. style.SetFont(font);
  2. //将新的样式赋给单元格
  3. cell.CellStyle = style;
  1.  


  1. 设置单元格宽高:
  1.   设置单元格的高度实际是设置其所在行高,所以要在单元格所在行上设置行高,行高设置数值好像是像素点的1/20,所以*20以便达到设置效果;
  1.   设置单元格的宽度实际上是设置其所在列宽,所以要在单元格所在列上设置(列的设置在工作表上),宽度数值好像是字符的1/256,所以*256以便达到设置效果。
  2.  
  1. //设置单元格的高度
  2. row.Height = 30 * 20;
  3. //设置单元格的宽度
  1. sheet.SetColumnWidth(0, 30 * 256);
  1. 合并单元格:合并单元格实际上是声明一个区域,该区域中的单元格将进行合并,合并后的内容与样式以该区域最左上角的单元格为准。
  1.  
  1. //设置一个合并单元格区域,使用上下左右定义CellRangeAddress区域
  2. //CellRangeAddress四个参数为:起始行,结束行,起始列,结束列
  3. sheet.AddMergedRegion(new CellRangeAddress(0, 0, 0, 10));
  4.  
  5. 添加公式:使用CellCellFormula来设置公式,是一个字符串,公式前不需要加=号。
  1.  
  1. //通过Cell的CellFormula向单元格中写入公式
  2. //注:直接写公式内容即可,不需要在最前加'='
  3. ICell cell2 = sheet.CreateRow(1).CreateCell(0);
  4. cell2.CellFormula = "HYPERLINK(\"测试图片.jpg\",\"测试图片.jpg\")";
  1. 将工作簿写入文件查看效果:
  1. //将工作簿写入文件
  2. using (FileStream fs = new FileStream("生成效果.xls", FileMode.Create, FileAccess.Write))
  3. {
  4. workbook.Write(fs);
  5. }
  1.  
  1. 最终效果:

  1.  

设置Excel的自动筛选功能

单元格数字格式的问题

NPOI向Excel文件中插入数值时,可能会出现数字当作文本的情况(即左上角有个绿色三角),这样单元格的值就无法参与运算。这是因为在SetCellValue设置单元格值的时候使用了字符串进行赋值,默认被转换成了字符型。如果需要纯数字型的,请向SetCellValue中设置数字型变量。

以上两个问题的示例代码如下:

  1. //建立空白工作薄
  2. IWorkbook workbook = new HSSFWorkbook();
  3.  
  4. //在工作薄中建立工作表
  5. ISheet sheet = workbook.CreateSheet();
  6.  
  7. //填充筛选的内容
  8. sheet.CreateRow(0).CreateCell(0).SetCellValue("省份");
  9. sheet.CreateRow(1).CreateCell(0).SetCellValue("河北省");
  10. sheet.CreateRow(2).CreateCell(0).SetCellValue("湖南省");
  11.  
  12. //验证数字格式问题
  13. sheet.GetRow(1).CreateCell(2).SetCellValue("123");
  14. sheet.GetRow(2).CreateCell(2).SetCellValue(123);
  15.  
  16. //设置Excel的自动筛选
  17. CellRangeAddress c = CellRangeAddress.ValueOf("A1");
  18. sheet.SetAutoFilter(c);
  19.  
  20. //写文件
  21. using (FileStream fs = new FileStream("haha.xls", FileMode.Create, FileAccess.Write))
  22. {
  23. workbook.Write(fs);
  24. }

最终的效果显示:

Npoi导入导出Excel操作

  1. using NPOI.HSSF.UserModel;
  2. using NPOI.SS.UserModel;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Data;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Text;
  9. using System.Threading.Tasks;
  10.  
  11. namespace HblGrabPro
  12. {
  13. class ExcelHelper
  14. {
  15. public static void DsToExcel(DataSet ds, string strExcelFileName)
  16. {
  17. HSSFWorkbook workbook = new HSSFWorkbook();
  18. foreach(DataTable dt in ds.Tables )
  19. {
  20. try
  21. {
  22. ISheet sheet = workbook.CreateSheet(string.IsNullOrEmpty(dt.TableName) ? Path.GetFileNameWithoutExtension(strExcelFileName) : dt.TableName);
  23. ICellStyle HeadercellStyle = workbook.CreateCellStyle();
  24. HeadercellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
  25. HeadercellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
  26. HeadercellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
  27. HeadercellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
  28. HeadercellStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
  29.  
  30. NPOI.SS.UserModel.IFont headerfont = workbook.CreateFont();
  31. headerfont.Boldweight = (short)FontBoldWeight.Bold;
  32. HeadercellStyle.SetFont(headerfont);
  33.  
  34. int icolIndex = 0;
  35. IRow headerRow = sheet.CreateRow(0);
  36. foreach (DataColumn item in dt.Columns)
  37. {
  38. ICell cell = headerRow.CreateCell(icolIndex);
  39. cell.SetCellValue(item.ColumnName);
  40. cell.CellStyle = HeadercellStyle;
  41. icolIndex++;
  42. }
  43.  
  44. ICellStyle cellStyle = workbook.CreateCellStyle();
  45. cellStyle.DataFormat = HSSFDataFormat.GetBuiltinFormat("@");
  46. cellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
  47. cellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
  48. cellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
  49. cellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
  50.  
  51. NPOI.SS.UserModel.IFont cellfont = workbook.CreateFont();
  52. cellfont.Boldweight = (short)FontBoldWeight.Normal;
  53. cellStyle.SetFont(cellfont);
  54.  
  55. //建立内容行
  56. int iRowIndex = 1;
  57. int iCellIndex = 0;
  58. foreach (DataRow Rowitem in dt.Rows)
  59. {
  60. IRow DataRow = sheet.CreateRow(iRowIndex);
  61. foreach (DataColumn Colitem in dt.Columns)
  62. {
  63.  
  64. ICell cell = DataRow.CreateCell(iCellIndex);
  65. cell.SetCellValue(Rowitem[Colitem].ToString());
  66. cell.CellStyle = cellStyle;
  67. iCellIndex++;
  68. }
  69. iCellIndex = 0;
  70. iRowIndex++;
  71. }
  72.  
  73. for (int i = 0; i < icolIndex; i++)
  74. {
  75. sheet.AutoSizeColumn(i);
  76. }
  77. }
  78. catch (Exception ex)
  79. {
  80. //ILog log = LogManager.GetLogger("Exception Log");
  81. //log.Error(ex.Message + Environment.NewLine + ex.StackTrace);
  82. ////记录AuditTrail
  83. //CCFS.Framework.BLL.AuditTrailBLL.LogAuditTrail(ex);
  84. continue;
  85. //MessageBox.Show(m_Common_ResourceManager.GetString("Export_to_excel_failed"), m_Common_ResourceManager.GetString("Information"), MessageBoxButtons.OK, MessageBoxIcon.Information);
  86. }
  87. }
  88. FileStream file = new FileStream(strExcelFileName, FileMode.OpenOrCreate);
  89. workbook.Write(file);
  90. file.Flush();
  91. file.Close();
  92. }
  93.  
  94. public static void DtToExcel(DataTable dt, string strExcelFileName)
  95. {
  96. HSSFWorkbook workbook = new HSSFWorkbook();
  97. try
  98. {
  99.  
  100. ISheet sheet = workbook.CreateSheet("Sheet1");
  101.  
  102. ICellStyle HeadercellStyle = workbook.CreateCellStyle();
  103. HeadercellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
  104. HeadercellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
  105. HeadercellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
  106. HeadercellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
  107. HeadercellStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
  108. //字体
  109. NPOI.SS.UserModel.IFont headerfont = workbook.CreateFont();
  110. headerfont.Boldweight = (short)FontBoldWeight.Bold;
  111. HeadercellStyle.SetFont(headerfont);
  112.  
  113. //用column name 作为列名
  114. int icolIndex = 0;
  115. IRow headerRow = sheet.CreateRow(0);
  116. foreach (DataColumn item in dt.Columns)
  117. {
  118. ICell cell = headerRow.CreateCell(icolIndex);
  119. cell.SetCellValue(item.ColumnName);
  120. cell.CellStyle = HeadercellStyle;
  121. icolIndex++;
  122. }
  123.  
  124. ICellStyle cellStyle = workbook.CreateCellStyle();
  125.  
  126. //为避免日期格式被Excel自动替换,所以设定 format 为 『@』 表示一率当成text來看
  127. cellStyle.DataFormat = HSSFDataFormat.GetBuiltinFormat("@");
  128. cellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
  129. cellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
  130. cellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
  131. cellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
  132.  
  133. NPOI.SS.UserModel.IFont cellfont = workbook.CreateFont();
  134. cellfont.Boldweight = (short)FontBoldWeight.Normal;
  135. cellStyle.SetFont(cellfont);
  136.  
  137. //建立内容行
  138. int iRowIndex = 1;
  139. int iCellIndex = 0;
  140. foreach (DataRow Rowitem in dt.Rows)
  141. {
  142. IRow DataRow = sheet.CreateRow(iRowIndex);
  143. foreach (DataColumn Colitem in dt.Columns)
  144. {
  145.  
  146. ICell cell = DataRow.CreateCell(iCellIndex);
  147. cell.SetCellValue(Rowitem[Colitem].ToString());
  148. cell.CellStyle = cellStyle;
  149. iCellIndex++;
  150. }
  151. iCellIndex = 0;
  152. iRowIndex++;
  153. }
  154.  
  155. //自适应列宽度
  156. for (int i = 0; i < icolIndex; i++)
  157. {
  158. sheet.AutoSizeColumn(i);
  159. }
  160.  
  161. //写Excel
  162. FileStream file = new FileStream(strExcelFileName, FileMode.OpenOrCreate);
  163. workbook.Write(file);
  164. file.Flush();
  165. file.Close();
  166.  
  167. //MessageBox.Show(m_Common_ResourceManager.GetString("Export_to_excel_successfully"), m_Common_ResourceManager.GetString("Information"), MessageBoxButtons.OK, MessageBoxIcon.Information);
  168. }
  169. catch (Exception ex)
  170. {
  171. //ILog log = LogManager.GetLogger("Exception Log");
  172. //log.Error(ex.Message + Environment.NewLine + ex.StackTrace);
  173. ////记录AuditTrail
  174. //CCFS.Framework.BLL.AuditTrailBLL.LogAuditTrail(ex);
  175.  
  176. //MessageBox.Show(m_Common_ResourceManager.GetString("Export_to_excel_failed"), m_Common_ResourceManager.GetString("Information"), MessageBoxButtons.OK, MessageBoxIcon.Information);
  177. }
  178. finally { workbook = null; }
  179.  
  180. }
  181.  
  182. public static DataTable ExcelToDt(string strFilePath, string strTableName, int iSheetIndex)
  183. {
  184.  
  185. string strExtName = Path.GetExtension(strFilePath);
  186.  
  187. DataTable dt = new DataTable();
  188. if (!string.IsNullOrEmpty(strTableName))
  189. {
  190. dt.TableName = strTableName;
  191. }
  192.  
  193. if (strExtName.Equals(".xls") || strExtName.Equals(".xlsx"))
  194. {
  195. using (FileStream file = new FileStream(strFilePath, FileMode.Open, FileAccess.Read))
  196. {
  197. HSSFWorkbook workbook = new HSSFWorkbook(file);
  198. ISheet sheet = workbook.GetSheetAt(iSheetIndex);
  199.  
  200. //列头
  201. foreach (ICell item in sheet.GetRow(sheet.FirstRowNum).Cells)
  202. {
  203. dt.Columns.Add(item.ToString(), typeof(string));
  204. }
  205.  
  206. //写入内容
  207. System.Collections.IEnumerator rows = sheet.GetRowEnumerator();
  208. while (rows.MoveNext())
  209. {
  210. IRow row = (HSSFRow)rows.Current;
  211. if (row.RowNum == sheet.FirstRowNum)
  212. {
  213. continue;
  214. }
  215.  
  216. DataRow dr = dt.NewRow();
  217. foreach (ICell item in row.Cells)
  218. {
  219. switch (item.CellType)
  220. {
  221. case CellType.Boolean:
  222. dr[item.ColumnIndex] = item.BooleanCellValue;
  223. break;
  224. case CellType.Error:
  225. //dr[item.ColumnIndex] = ErrorEval.GetText(item.ErrorCellValue);
  226. break;
  227. case CellType.Formula:
  228. switch (item.CachedFormulaResultType)
  229. {
  230. case CellType.Boolean:
  231. dr[item.ColumnIndex] = item.BooleanCellValue;
  232. break;
  233. case CellType.Error:
  234. //dr[item.ColumnIndex] = ErrorEval.GetText(item.ErrorCellValue);
  235. break;
  236. case CellType.Numeric:
  237. if (DateUtil.IsCellDateFormatted(item))
  238. {
  239. dr[item.ColumnIndex] = item.DateCellValue.ToString("yyyy-MM-dd hh:MM:ss");
  240. }
  241. else
  242. {
  243. dr[item.ColumnIndex] = item.NumericCellValue;
  244. }
  245. break;
  246. case CellType.String:
  247. string str = item.StringCellValue;
  248. if (!string.IsNullOrEmpty(str))
  249. {
  250. dr[item.ColumnIndex] = str.ToString();
  251. }
  252. else
  253. {
  254. dr[item.ColumnIndex] = null;
  255. }
  256. break;
  257. case CellType.Unknown:
  258. case CellType.Blank:
  259. default:
  260. dr[item.ColumnIndex] = string.Empty;
  261. break;
  262. }
  263. break;
  264. case CellType.Numeric:
  265. if (DateUtil.IsCellDateFormatted(item))
  266. {
  267. dr[item.ColumnIndex] = item.DateCellValue.ToString("yyyy-MM-dd hh:MM:ss");
  268. }
  269. else
  270. {
  271. dr[item.ColumnIndex] = item.NumericCellValue;
  272. }
  273. break;
  274. case CellType.String:
  275. string strValue = item.StringCellValue;
  276. if (string.IsNullOrEmpty(strValue))
  277. {
  278. dr[item.ColumnIndex] = strValue.ToString();
  279. }
  280. else
  281. {
  282. dr[item.ColumnIndex] = null;
  283. }
  284. break;
  285. case CellType.Unknown:
  286. case CellType.Blank:
  287. default:
  288. dr[item.ColumnIndex] = string.Empty;
  289. break;
  290. }
  291. }
  292. dt.Rows.Add(dr);
  293. }
  294. }
  295. }
  296.  
  297. return dt;
  298. }
  299. }
  300. }
  1.  

用NPOI操作EXCEL--生成下拉列表

      上一节我们讲了简单的数据有效性验证,这一节我们学习一下数据有效性的另一个应用--下拉列表。在Excel中,并没有类似Web中的下拉控件,其下拉效果是通过数据有效性来实现的。设置步骤为:
(1)选定一个要生成下拉列表的区域;
(2)设置数据有效性为序列,并在来源中填充可选下拉的值,用“,”隔开(如图)。

对应的效果为:

同样,利用NPOI代码也可以实现上面的效果:

HSSFSheet sheet1 = hssfworkbook.CreateSheet("Sheet1");

CellRangeAddressList regions = new CellRangeAddressList(0, 65535, 0, 0);
DVConstraint constraint = DVConstraint.CreateExplicitListConstraint(new string[] { "itemA", "itemB", "itemC" });
HSSFDataValidation dataValidate = new HSSFDataValidation(regions, constraint);
sheet1.AddValidationData(dataValidate);

下面对代码作一下简要说明:
先设置一个需要提供下拉的区域,关于CellRangeAddressList构造函数参数的说明请参见上一节

CellRangeAddressList regions = new CellRangeAddressList(0, 65535, 0, 0);

然后将下拉项作为一个数组传给CreateExplicitListConstraint作为参数创建一个约束,根据要控制的区域和约束创建数据有效性就可以了。

但是这样会有一个问题:Excel中允许输入的序列来源长度最大为255个字符,也就是说当下拉项的总字符串长度超过255是将会出错。那么如果下拉项很多的情况下应该怎么处理呢?答案是通过引用的方式。步骤如下:
先创建一个Sheet专门用于存储下拉项的值,并将各下拉项的值写入其中:

HSSFSheet sheet2 = hssfworkbook.CreateSheet("ShtDictionary");
sheet2.CreateRow(0).CreateCell(0).SetCellValue("itemA");
sheet2.CreateRow(1).CreateCell(0).SetCellValue("itemB");
sheet2.CreateRow(2).CreateCell(0).SetCellValue("itemC");

然后定义一个名称,指向刚才创建的下拉项的区域:

HSSFName range = hssfworkbook.CreateName();
range.Reference = "ShtDictionary!$A1:$A3";
range.NameName = "dicRange";

最后,设置数据约束时指向这个名称而不是字符数组:

HSSFSheet sheet1 = hssfworkbook.CreateSheet("Sheet1");
CellRangeAddressList regions = new CellRangeAddressList(0, 65535, 0, 0);

DVConstraint constraint = DVConstraint.CreateFormulaListConstraint("dicRange");
HSSFDataValidation dataValidate = new HSSFDataValidation(regions, constraint);
sheet1.AddValidationData(dataValidate);

执行这段代码,生成的Excel效果如下:

在名称管理器中会发现有一个名为"dicRange"的名称,指向"ShtDictionary!$A1:$A3"的下拉项区域:

在数据有效性中会发现来源变成了"=dicRange",指向上面定义的名称。而不是以前的"itemA,itemB,itemC":

  1.  

NPOI之Excel——合并单元格、设置样式、输入公式的更多相关文章

  1. NPOI之Excel——合并单元格、设置样式、输入公式、设置筛选等

    首先建立一个空白的工作簿用作测试,并在其中建立空白工作表,在表中建立空白行,在行中建立单元格,并填入内容: //建立空白工作簿 IWorkbook workbook = new HSSFWorkboo ...

  2. 创建excel,合并单元格,设置单元格样式

    package com.huawei.excel; import java.io.File;import java.io.FileOutputStream;import java.util.Date; ...

  3. npoi导出excel合并单元格

    需要引用NPOI.dll程序集和Ionic.Zip.dll程序集 string[] headerRowName = { "序号", "地市", "镇街 ...

  4. NPOI.dll 用法。单元格,样式,字体,颜色,行高,宽度。读写excel

    NPOI.dll 用法.单元格,样式,字体,颜色,行高,宽度.读写excel 转载:http://yuncode.net/code/c_531e679b3896495 view source prin ...

  5. asp.net C#取Excel 合并单元格内容

    asp教程.net c#取excel 合并单元格内容读取excel数据,填充dataset// 连接字符串 string xlspath = server.mappath("~/www.11 ...

  6. NPOI 生成Excel (单元格合并、设置单元格样式:字段,颜色、设置单元格为下拉框并限制输入值、设置单元格只能输入数字等)

    NPIO源码地址:https://github.com/tonyqus/npoi NPIO使用参考:源码中的 NPOITest项目 下面代码包括: 1.包含多个Sheet的Excel 2.单元格合并 ...

  7. 转载 NPOI.dll 用法。单元格,样式,字体,颜色,行高,宽度。读写excel

    我用的版本是1.25的.每个版本用法有一点不同 using System; using System.Collections.Generic; using System.ComponentModel; ...

  8. java poi导出Excel合并单元格并设置边框

    import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFCellStyle; i ...

  9. C# NPOI Excel 合并单元格和取消单元格

    1.合并单元操作 //合并单元格 /** 第一个参数:从第几行开始合并 第二个参数:到第几行结束合并 第三个参数:从第几列开始合并 第四个参数:到第几列结束合并 **/ CellRangeAddres ...

随机推荐

  1. NSKeyValueObserving(KVO)

    NSKeyValueObserving非正式协议定义了一种机制,它允许对象去监听其它对象的某个属性的修改. 我们可以监听一个对象的属性,包括简单属性,一对一的关系,和一对多的关系.一对多关系的监听者会 ...

  2. Silverlight 调用 aspx 相关文件

    private void Button_Click_1(object sender, RoutedEventArgs e) { WebClient wb = new WebClient(); wb.D ...

  3. C#判断字符串为空

    string str = null; if (string.IsNullOrWhiteSpace(str)) { MessageBox.Show("字符串为null"); } if ...

  4. sharepoint 2010 切换域

    前提: 现在已经有一个sharepoint 2010的环境,当前域为contosoA.com,有个需求需要将这个域切换到域contosoB.com.下面是成功操作的步骤. 1.数据最重要 备份所有数据 ...

  5. VC++ MFC 如何实现在编辑框中输出具有换行功能的文段 01

    很久不来写东西了,昨天睡觉前写个小工具,突然,这玩意不会换行怎么整... 首先是第一步,获取字符串的长度,转载自白乔的文章. ------------------------------------- ...

  6. Spring Mvc 输出Json(iwantmoon.com出品)

    原文:http://iwantmoon.com/Post/f94e49caf9b6455db7158474bab4c4dd 因为工作需要,现在要去做开放平台,考虑了多种方案之后,基本确定 下来,Htt ...

  7. Cannot install ubuntu or other linux flavours on citrix Xen server

    Citrix Xen sucks! When u try to install linux stuff on its Xen servers, u will get an error complain ...

  8. 三分--Football Goal(面积最大)

    B - Football Goal Time Limit:500MS     Memory Limit:65536KB     64bit IO Format:%I64d & %I64u Su ...

  9. IDEA for Mac 解决控制台乱码问题

    近期发现 idea for mac 版本中 tomcat 控制台有中文的地方出现乱码问题,其实很简单就可以解决. 这里做个笔记,以后可以方便不会的人来解决 ---------------------- ...

  10. ACM--South Pacific 2012

    题目链接:https://icpcarchive.ecs.baylor.edu/index.php?option=com_onlinejudge&Itemid=8&category=5 ...