资讯专栏INFORMATION COLUMN

Java实现excel导入导出学习笔记2 - 利用xml技术设置导入模板,设置excel样式

I_Am / 962人阅读

摘要:四个参数分别是起始行终止行起始列终止列数据有效性对象包下载百度云盘外链

xml文件

</>复制代码

  1. <span class="hljs-tag"></<span class="hljs-name">li</span>></span><span class="hljs-tag"><<span class="hljs-name">li</span>></span> <span class="hljs-tag"><<span class="hljs-name">tr</span> <span class="hljs-attr">height</span>=<span class="hljs-string">"16px"</span>></span><span class="hljs-tag"></<span class="hljs-name">li</span>></span><span class="hljs-tag"><<span class="hljs-name">li</span>></span> <span class="hljs-tag"><<span class="hljs-name">td</span> <span class="hljs-attr">rowspan</span>=<span class="hljs-string">"1"</span> <span class="hljs-attr">colspan</span>=<span class="hljs-string">"6"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"学生信息导入"</span> /></span><span class="hljs-tag"></<span class="hljs-name">li</span>></span><span class="hljs-tag"><<span class="hljs-name">li</span>></span> <span class="hljs-tag"></<span class="hljs-name">tr</span>></span><span class="hljs-tag"></<span class="hljs-name">li</span>></span><span class="hljs-tag"><<span class="hljs-name">li</span>></span>
execel的行和列以0开头 设置单元格居中

HSSFCellStyle cellStyle = wb.createCellStyle();//创建单元格样式
cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);//设置单元格对齐方式

设置单元格字体

</>复制代码

  1. HSSFFont font = wb.createFont();
  2. font.setFontName("仿宋_GB2312");
  3. font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);//字体加粗
  4. //font.setFontHeight((short)12);
  5. font.setFontHeightInPoints((short)12);
  6. cellStyle.setFont(font);
  7. cell.setCellStyle(cellStyle);
//合并单元格居中

</>复制代码

  1. sheet.addMergedRegion(new CellRangeAddress(rspan, rspan, 0, cspan));
设置单元格数据类型

</>复制代码

  1. /**
  2. * 测试单元格样式
  3. * @author David
  4. * @param wb
  5. * @param cell
  6. * @param td
  7. */
  8. private static void setType(HSSFWorkbook wb, HSSFCell cell, Element td) {
  9. Attribute typeAttr = td.getAttribute("type");
  10. String type = typeAttr.getValue();
  11. HSSFDataFormat format = wb.createDataFormat();
  12. HSSFCellStyle cellStyle = wb.createCellStyle();
  13. if("NUMERIC".equalsIgnoreCase(type)){
  14. cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
  15. Attribute formatAttr = td.getAttribute("format");
  16. String formatValue = formatAttr.getValue();
  17. formatValue = StringUtils.isNotBlank(formatValue)? formatValue : "#,##0.00";
  18. cellStyle.setDataFormat(format.getFormat(formatValue));
  19. }else if("STRING".equalsIgnoreCase(type)){
  20. cell.setCellValue("");
  21. cell.setCellType(HSSFCell.CELL_TYPE_STRING);
  22. cellStyle.setDataFormat(format.getFormat("@"));
  23. }else if("DATE".equalsIgnoreCase(type)){
  24. cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
  25. cellStyle.setDataFormat(format.getFormat("yyyy-m-d"));
  26. }else if("ENUM".equalsIgnoreCase(type)){
  27. CellRangeAddressList regions =
  28. new CellRangeAddressList(cell.getRowIndex(), cell.getRowIndex(),
  29. cell.getColumnIndex(), cell.getColumnIndex());
  30. Attribute enumAttr = td.getAttribute("format");
  31. String enumValue = enumAttr.getValue();
  32. //加载下拉列表内容
  33. DVConstraint constraint =
  34. DVConstraint.createExplicitListConstraint(enumValue.split(","));
  35. //数据有效性对象
  36. HSSFDataValidation dataValidation = new HSSFDataValidation(regions, constraint);
  37. wb.getSheetAt(0).addValidationData(dataValidation);
  38. }
  39. cell.setCellStyle(cellStyle);
  40. }
设置下拉列表类型

封装设置数据有效性方法

</>复制代码

  1. /**
  2. * 方法名称:SetDataValidation
  3. * 内容摘要:设置数据有效性
  4. * @param sheet excel sheet內容
  5. * @param textList 下拉列表
  6. * @param firstRow 單元格範圍
  7. * @param firstCol
  8. * @param endRow
  9. * @param endCol
  10. */
  11. private static HSSFDataValidation setDataValidation(HSSFSheet sheet,String[] textList,short firstRow,short firstCol, short endRow, short endCol) {
  12. //加载下拉列表内容
  13. DVConstraint constraint = DVConstraint.createExplicitListConstraint(textList);
  14. //设置数据有效性加载在哪个单元格上。
  15. //四个参数分别是:起始行、终止行、起始列、终止列
  16. CellRangeAddressList regions = new CellRangeAddressList(firstRow,endRow, firstCol, endCol);
  17. //数据有效性对象
  18. HSSFDataValidation data_validation = new HSSFDataValidation(regions, constraint);
  19. sheet.addValidationData(data_validation);
  20. return data_validation;
  21. }
设置列宽方法封装

</>复制代码

  1. /**
  2. * 设置列宽
  3. * @author David
  4. * @param sheet
  5. * @param colgroup
  6. */
  7. private static void setColumnWidth(HSSFSheet sheet, Element colgroup) {
  8. List cols = colgroup.getChildren("col");
  9. for (int i = 0; i < cols.size(); i++) {
  10. Element col = cols.get(i);
  11. Attribute width = col.getAttribute("width");
  12. String unit = width.getValue().replaceAll("[0-9,.]", "");//截取单位
  13. String value = width.getValue().replaceAll(unit, "");//擦除单位
  14. int v=0;
  15. //单位转化
  16. if(StringUtils.isBlank(unit) || "px".endsWith(unit)){//如果单位为空或等于px
  17. v = Math.round(Float.parseFloat(value) * 37F);
  18. }else if ("em".endsWith(unit)){//如果单位为em
  19. v = Math.round(Float.parseFloat(value) * 267.5F);
  20. }
  21. sheet.setColumnWidth(i, v);//设置第i列宽度为v
  22. }
  23. }

完整代码

</>复制代码

  1. package com.imooc.excel;
  2. import org.apache.commons.io.FileUtils;
  3. import org.apache.commons.lang3.StringUtils;
  4. import org.apache.poi.hssf.usermodel.*;
  5. import org.apache.poi.ss.util.CellRangeAddress;
  6. import org.apache.poi.ss.util.CellRangeAddressList;
  7. import org.jdom.Attribute;
  8. import org.jdom.Document;
  9. import org.jdom.Element;
  10. import org.jdom.input.SAXBuilder;
  11. import java.io.File;
  12. import java.io.FileOutputStream;
  13. import java.util.List;
  14. /**
  15. * Created by chenld1 on 2015/10/6.
  16. */
  17. public class CreateTemplate {
  18. /**
  19. * 创建模板文件
  20. * @author David
  21. * @param args
  22. */
  23. public static void main(String[] args) {
  24. //获取解析xml文件路径
  25. String path = System.getProperty("user.dir") + "/student2.xml";
  26. File file = new File(path);
  27. SAXBuilder builder = new SAXBuilder();
  28. try {
  29. //解析xml文件
  30. Document parse = builder.build(file);
  31. //创建Excel
  32. HSSFWorkbook wb = new HSSFWorkbook();
  33. //创建sheet
  34. HSSFSheet sheet = wb.createSheet("Sheet0");
  35. //获取xml文件跟节点
  36. Element root = parse.getRootElement();
  37. //获取模板名称
  38. String templateName = root.getAttribute("name").getValue();
  39. int rownum = 0;
  40. int column = 0;
  41. //设置列宽
  42. Element colgroup = root.getChild("colgroup");
  43. setColumnWidth(sheet,colgroup);
  44. //设置标题
  45. Element title = root.getChild("title");
  46. List trs = title.getChildren("tr");
  47. for (int i = 0; i < trs.size(); i++) {
  48. Element tr = trs.get(i);
  49. List tds = tr.getChildren("td");
  50. HSSFRow row = sheet.createRow(rownum);
  51. HSSFCellStyle cellStyle = wb.createCellStyle();//创建单元格样式
  52. cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);//设置单元格对齐方式
  53. for(column = 0;column ths = tr.getChildren("th");
  54. for(column = 0;column < ths.size();column++){
  55. Element th = ths.get(column);
  56. Attribute valueAttr = th.getAttribute("value");
  57. HSSFCell cell = row.createCell(column);
  58. if(valueAttr != null){
  59. String value =valueAttr.getValue();
  60. cell.setCellValue(value);
  61. }
  62. }
  63. rownum++;
  64. }
  65. //设置数据区域样式
  66. Element tbody = root.getChild("tbody");
  67. Element tr = tbody.getChild("tr");
  68. int repeat = tr.getAttribute("repeat").getIntValue();
  69. List tds = tr.getChildren("td");
  70. for (int i = 0; i < repeat; i++) {
  71. HSSFRow row = sheet.createRow(rownum);
  72. for(column =0 ;column < tds.size();column++){
  73. Element td = tds.get(column);
  74. HSSFCell cell = row.createCell(column);
  75. setType(wb,cell,td);
  76. }
  77. rownum++;
  78. }
  79. //生成Excel导入模板
  80. File tempFile = new File("e:/" + templateName + ".xls");
  81. tempFile.delete();
  82. tempFile.createNewFile();
  83. FileOutputStream stream = FileUtils.openOutputStream(tempFile);
  84. wb.write(stream);
  85. stream.close();
  86. } catch (Exception e) {
  87. e.printStackTrace();
  88. }
  89. }
  90. /**
  91. * 设置单元格数据类型
  92. * @author David
  93. * @param wb
  94. * @param cell
  95. * @param td
  96. */
  97. private static void setType(HSSFWorkbook wb, HSSFCell cell, Element td) {
  98. Attribute typeAttr = td.getAttribute("type");
  99. String type = typeAttr.getValue();
  100. //HSSFDataformat
  101. HSSFDataFormat format = wb.createDataFormat();
  102. HSSFCellStyle cellStyle = wb.createCellStyle();
  103. if("NUMERIC".equalsIgnoreCase(type)){
  104. cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
  105. Attribute formatAttr = td.getAttribute("format");
  106. String formatValue = formatAttr.getValue();
  107. formatValue = StringUtils.isNotBlank(formatValue)? formatValue : "#,##0.00";
  108. cellStyle.setDataFormat(format.getFormat(formatValue));
  109. }else if("STRING".equalsIgnoreCase(type)){
  110. cell.setCellValue("");
  111. cell.setCellType(HSSFCell.CELL_TYPE_STRING);
  112. cellStyle.setDataFormat(format.getFormat("@"));
  113. }else if("DATE".equalsIgnoreCase(type)){
  114. cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
  115. cellStyle.setDataFormat(format.getFormat("yyyy-m-d"));
  116. }else if("ENUM".equalsIgnoreCase(type)){
  117. CellRangeAddressList regions =
  118. new CellRangeAddressList(cell.getRowIndex(), cell.getRowIndex(),
  119. cell.getColumnIndex(), cell.getColumnIndex());
  120. Attribute enumAttr = td.getAttribute("format");
  121. String enumValue = enumAttr.getValue();
  122. //加载下拉列表内容
  123. DVConstraint constraint =
  124. DVConstraint.createExplicitListConstraint(enumValue.split(","));
  125. //数据有效性对象
  126. HSSFDataValidation dataValidation = new HSSFDataValidation(regions, constraint);
  127. wb.getSheetAt(0).addValidationData(dataValidation);
  128. }
  129. cell.setCellStyle(cellStyle);
  130. }
  131. /**
  132. * 设置列宽
  133. * @author David
  134. * @param sheet
  135. * @param colgroup
  136. */
  137. private static void setColumnWidth(HSSFSheet sheet, Element colgroup) {
  138. List cols = colgroup.getChildren("col");
  139. for (int i = 0; i < cols.size(); i++) {
  140. Element col = cols.get(i);
  141. Attribute width = col.getAttribute("width");
  142. String unit = width.getValue().replaceAll("[0-9,.]", "");//截取单位
  143. String value = width.getValue().replaceAll(unit, "");//擦除单位
  144. int v=0;
  145. //单位转化
  146. if(StringUtils.isBlank(unit) || "px".endsWith(unit)){//如果单位为空或等于px
  147. v = Math.round(Float.parseFloat(value) * 37F);
  148. }else if ("em".endsWith(unit)){//如果单位为em
  149. v = Math.round(Float.parseFloat(value) * 267.5F);
  150. }
  151. sheet.setColumnWidth(i, v);//设置第i列宽度为v
  152. }
  153. }
  154. /**
  155. * 方法名称:SetDataValidation
  156. * 内容摘要:设置数据有效性
  157. * @param sheet excel sheet內容
  158. * @param textList 下拉列表
  159. * @param firstRow 單元格範圍
  160. * @param firstCol
  161. * @param endRow
  162. * @param endCol
  163. */
  164. private static HSSFDataValidation setDataValidation(HSSFSheet sheet,String[] textList,short firstRow,short firstCol, short endRow, short endCol) {
  165. //加载下拉列表内容
  166. DVConstraint constraint = DVConstraint.createExplicitListConstraint(textList);
  167. //设置数据有效性加载在哪个单元格上。
  168. //四个参数分别是:起始行、终止行、起始列、终止列
  169. CellRangeAddressList regions = new CellRangeAddressList(firstRow,endRow, firstCol, endCol);
  170. //数据有效性对象
  171. HSSFDataValidation data_validation = new HSSFDataValidation(regions, constraint);
  172. sheet.addValidationData(data_validation);
  173. return data_validation;
  174. }
  175. }
jar包下载

百度云盘外链

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/64637.html

相关文章

  • Java实现excel导入导出学习笔记1 - 实现方式

    摘要:需要的技术框架利用其上传下载功能解析技术定制导入模板制作前台与格式对应,版本低,兼容性好与格式对应组成的几个概念工作薄工作表行记录单元格创建中的的详见如创建创建工作簿创建工作表创建第一行创建一个文件存盘名字性別男解析文件创建,读取文件 需要的技术 1、strut2框架 利用其上传下载功能2、xml解析技术 定制导入模板3、jquery UI 制作前台 4、showImg(/i...

    wean 评论0 收藏0
  • 慕课网_《解密JAVA实现Excel导入导出学习总结

    时间:2017年07月06日星期四说明:本文部分内容均来自慕课网。@慕课网:http://www.imooc.com教学源码:无学习源码:https://github.com/zccodere/s... 第一章:课程介绍 1-1 预备知识 基础知识 struts2框架(上传下载功能) xml解析技术(导入模板) JQuery EasyUI(前台美观) 课程目录 实现方式 定制导入模版 导入文件 导...

    enrecul101 评论0 收藏0
  • Java Excel导入导出,基于XML和Easy-excel使用

    摘要:我想能不能像配置文件一样可配置的导入导出,那样使用起来就方便许多。配置和使用下面是员工信息模型。支持多种映射,使用英文逗号进行分割。导入时它会以分割前面的作为导入时使用的值,后面的作为导出时使用的值后面值进行逆推导出时同理。 1.前言 在工作时,遇到过这样的需求,需要灵活的对工单进行导入或导出,以前自己也做过,但使用不灵活繁琐。我想能不能像配置文件一样可配置的导入导出,那样使用起来就方...

    13651657101 评论0 收藏0
  • 从零开始,SpreadJS新人学习笔记【第5周】

    摘要:复制粘贴单元格格式和单元格类型本周,让我们一起来学习的复制粘贴单元格格式和单元格类型,希望我的学习笔记能够帮助你们,从零开始学习,并逐步精通。 复制粘贴、单元格格式和单元格类型 本周,让我们一起来学习SpreadJS 的复制粘贴、单元格格式和单元格类型,希望我的学习笔记能够帮助你们,从零开始学习 SpreadJS,并逐步精通。 在此前的学习笔记中,相信大家已经学会并熟练掌握了Sprea...

    shadowbook 评论0 收藏0

发表评论

0条评论

I_Am

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<