在路上

 找回密码
 立即注册
在路上 站点首页 学习 查看内容

Poi实现Excel导出工具类封装

2016-12-20 13:15| 发布者: zhangjf| 查看: 467| 评论: 0

摘要: 工具类代码PoiExcelExport如下: package com.myssm.util.poi;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.OutputStream;import java.lang.reflect.Method;im ...

工具类代码PoiExcelExport如下:

  1. package com.myssm.util.poi;
  2. import java.io.File;
  3. import java.io.FileOutputStream;
  4. import java.io.IOException;
  5. import java.io.OutputStream;
  6. import java.lang.reflect.Method;
  7. import java.net.URLEncoder;
  8. import java.text.DecimalFormat;
  9. import java.util.List;
  10. import javax.servlet.http.HttpServletResponse;
  11. import org.apache.poi.hssf.usermodel.HSSFCellStyle;
  12. import org.apache.poi.hssf.usermodel.HSSFFont;
  13. import org.apache.poi.hssf.usermodel.HSSFPalette;
  14. import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  15. import org.apache.poi.ss.usermodel.Cell;
  16. import org.apache.poi.ss.usermodel.CellStyle;
  17. import org.apache.poi.ss.usermodel.Row;
  18. import org.apache.poi.ss.usermodel.Sheet;
  19. import org.apache.poi.ss.util.CellRangeAddress;
  20. public class PoiExcelExport {
  21. HttpServletResponse response;
  22. // 文件名
  23. private String fileName ;
  24. //文件保存路径
  25. private String fileDir;
  26. //sheet名
  27. private String sheetName;
  28. //表头字体
  29. private String titleFontType = "Arial Unicode MS";
  30. //表头背景色
  31. private String titleBackColor = "C1FBEE";
  32. //表头字号
  33. private short titleFontSize = 12;
  34. //添加自动筛选的列 如 A:M
  35. private String address = "";
  36. //正文字体
  37. private String contentFontType = "Arial Unicode MS";
  38. //正文字号
  39. private short contentFontSize = 12;
  40. //Float类型数据小数位
  41. private String floatDecimal = ".00";
  42. //Double类型数据小数位
  43. private String doubleDecimal = ".00";
  44. //设置列的公式
  45. private String colFormula[] = null;
  46. DecimalFormat floatDecimalFormat=new DecimalFormat(floatDecimal);
  47. DecimalFormat doubleDecimalFormat=new DecimalFormat(doubleDecimal);
  48. private HSSFWorkbook workbook = null;
  49. public PoiExcelExport(String fileDir,String sheetName){
  50. this.fileDir = fileDir;
  51. this.sheetName = sheetName;
  52. workbook = new HSSFWorkbook();
  53. }
  54. public PoiExcelExport(HttpServletResponse response,String fileName,String sheetName){
  55. this.response = response;
  56. this.sheetName = sheetName;
  57. workbook = new HSSFWorkbook();
  58. }
  59. /**
  60. * 设置表头字体.
  61. * @param titleFontType
  62. */
  63. public void setTitleFontType(String titleFontType) {
  64. this.titleFontType = titleFontType;
  65. }
  66. /**
  67. * 设置表头背景色.
  68. * @param titleBackColor 十六进制
  69. */
  70. public void setTitleBackColor(String titleBackColor) {
  71. this.titleBackColor = titleBackColor;
  72. }
  73. /**
  74. * 设置表头字体大小.
  75. * @param titleFontSize
  76. */
  77. public void setTitleFontSize(short titleFontSize) {
  78. this.titleFontSize = titleFontSize;
  79. }
  80. /**
  81. * 设置表头自动筛选栏位,如A:AC.
  82. * @param address
  83. */
  84. public void setAddress(String address) {
  85. this.address = address;
  86. }
  87. /**
  88. * 设置正文字体.
  89. * @param contentFontType
  90. */
  91. public void setContentFontType(String contentFontType) {
  92. this.contentFontType = contentFontType;
  93. }
  94. /**
  95. * 设置正文字号.
  96. * @param contentFontSize
  97. */
  98. public void setContentFontSize(short contentFontSize) {
  99. this.contentFontSize = contentFontSize;
  100. }
  101. /**
  102. * 设置float类型数据小数位 默认.00
  103. * @param doubleDecimal 如 ".00"
  104. */
  105. public void setDoubleDecimal(String doubleDecimal) {
  106. this.doubleDecimal = doubleDecimal;
  107. }
  108. /**
  109. * 设置doubel类型数据小数位 默认.00
  110. * @param floatDecimalFormat 如 ".00
  111. */
  112. public void setFloatDecimalFormat(DecimalFormat floatDecimalFormat) {
  113. this.floatDecimalFormat = floatDecimalFormat;
  114. }
  115. /**
  116. * 设置列的公式
  117. * @param colFormula 存储i-1列的公式 涉及到的行号使用@替换 如A@+B@
  118. */
  119. public void setColFormula(String[] colFormula) {
  120. this.colFormula = colFormula;
  121. }
  122. /**
  123. * 写excel.
  124. * @param titleColumn 对应bean的属性名
  125. * @param titleName excel要导出的表名
  126. * @param titleSize 列宽
  127. * @param dataList 数据
  128. */
  129. public void wirteExcel(String titleColumn[],String titleName[],int titleSize[],List<?> dataList){
  130. //添加Worksheet(不添加sheet时生成的xls文件打开时会报错)
  131. Sheet sheet = workbook.createSheet(this.sheetName);
  132. //新建文件
  133. OutputStream out = null;
  134. try {
  135. if(fileDir!=null){
  136. //有文件路径
  137. out = new FileOutputStream(fileDir);
  138. }else{
  139. //否则,直接写到输出流中
  140. out = response.getOutputStream();
  141. fileName = fileName+".xls";
  142. response.setContentType("application/x-msdownload");
  143. response.setHeader("Content-Disposition", "attachment; filename="
  144. + URLEncoder.encode(fileName, "UTF-8"));
  145. }
  146. //写入excel的表头
  147. Row titleNameRow = workbook.getSheet(sheetName).createRow(0);
  148. //设置样式
  149. HSSFCellStyle titleStyle = workbook.createCellStyle();
  150. titleStyle = (HSSFCellStyle) setFontAndBorder(titleStyle, titleFontType, (short) titleFontSize);
  151. titleStyle = (HSSFCellStyle) setColor(titleStyle, titleBackColor, (short)10);
  152. for(int i = 0;i < titleName.length;i++){
  153. sheet.setColumnWidth(i, titleSize[i]*256); //设置宽度
  154. Cell cell = titleNameRow.createCell(i);
  155. cell.setCellStyle(titleStyle);
  156. cell.setCellValue(titleName[i].toString());
  157. }
  158. //为表头添加自动筛选
  159. if(!"".equals(address)){
  160. CellRangeAddress c = (CellRangeAddress) CellRangeAddress.valueOf(address);
  161. sheet.setAutoFilter(c);
  162. }
  163. //通过反射获取数据并写入到excel中
  164. if(dataList!=null&&dataList.size()>0){
  165. //设置样式
  166. HSSFCellStyle dataStyle = workbook.createCellStyle();
  167. titleStyle = (HSSFCellStyle) setFontAndBorder(titleStyle, contentFontType, (short) contentFontSize);
  168. if(titleColumn.length>0){
  169. for(int rowIndex = 1;rowIndex<=dataList.size();rowIndex++){
  170. Object obj = dataList.get(rowIndex-1); //获得该对象
  171. Class clsss = obj.getClass(); //获得该对对象的class实例
  172. Row dataRow = workbook.getSheet(sheetName).createRow(rowIndex);
  173. for(int columnIndex = 0;columnIndex<titleColumn.length;columnIndex++){
  174. String title = titleColumn[columnIndex].toString().trim();
  175. if(!"".equals(title)){ //字段不为空
  176. //使首字母大写
  177. String UTitle = Character.toUpperCase(title.charAt(0))+ title.substring(1, title.length()); // 使其首字母大写;
  178. String methodName = "get"+UTitle;
  179. // 设置要执行的方法
  180. Method method = clsss.getDeclaredMethod(methodName);
  181. //获取返回类型
  182. String returnType = method.getReturnType().getName();
  183. String data = method.invoke(obj)==null?"":method.invoke(obj).toString();
  184. Cell cell = dataRow.createCell(columnIndex);
  185. if(data!=null&&!"".equals(data)){
  186. if("int".equals(returnType)){
  187. cell.setCellValue(Integer.parseInt(data));
  188. }else if("long".equals(returnType)){
  189. cell.setCellValue(Long.parseLong(data));
  190. }else if("float".equals(returnType)){
  191. cell.setCellValue(floatDecimalFormat.format(Float.parseFloat(data)));
  192. }else if("double".equals(returnType)){
  193. cell.setCellValue(doubleDecimalFormat.format(Double.parseDouble(data)));
  194. }else{
  195. cell.setCellValue(data);
  196. }
  197. }
  198. }else{ //字段为空 检查该列是否是公式
  199. if(colFormula!=null){
  200. String sixBuf = colFormula[columnIndex].replace("@", (rowIndex+1)+"");
  201. Cell cell = dataRow.createCell(columnIndex);
  202. cell.setCellFormula(sixBuf.toString());
  203. }
  204. }
  205. }
  206. }
  207. }
  208. }
  209. workbook.write(out);
  210. } catch (Exception e) {
  211. e.printStackTrace();
  212. } finally {
  213. try {
  214. out.close();
  215. } catch (IOException e) {
  216. e.printStackTrace();
  217. }
  218. }
  219. }
  220. /**
  221. * 将16进制的颜色代码写入样式中来设置颜色
  222. * @param style 保证style统一
  223. * @param color 颜色:66FFDD
  224. * @param index 索引 8-64 使用时不可重复
  225. * @return
  226. */
  227. public CellStyle setColor(CellStyle style,String color,short index){
  228. if(color!=""&&color!=null){
  229. //转为RGB码
  230. int r = Integer.parseInt((color.substring(0,2)),16); //转为16进制
  231. int g = Integer.parseInt((color.substring(2,4)),16);
  232. int b = Integer.parseInt((color.substring(4,6)),16);
  233. //自定义cell颜色
  234. HSSFPalette palette = workbook.getCustomPalette();
  235. palette.setColorAtIndex((short)index, (byte) r, (byte) g, (byte) b);
  236. style.setFillPattern(CellStyle.SOLID_FOREGROUND);
  237. style.setFillForegroundColor(index);
  238. }
  239. return style;
  240. }
  241. /**
  242. * 设置字体并加外边框
  243. * @param style 样式
  244. * @param style 字体名
  245. * @param style 大小
  246. * @return
  247. */
  248. public CellStyle setFontAndBorder(CellStyle style,String fontName,short size){
  249. HSSFFont font = workbook.createFont();
  250. font.setFontHeightInPoints(size);
  251. font.setFontName(fontName);
  252. font.setBold(true);
  253. style.setFont(font);
  254. style.setBorderBottom(CellStyle.BORDER_THIN); //下边框
  255. style.setBorderLeft(CellStyle.BORDER_THIN);//左边框
  256. style.setBorderTop(CellStyle.BORDER_THIN);//上边框
  257. style.setBorderRight(CellStyle.BORDER_THIN);//右边框
  258. return style;
  259. }
  260. /**
  261. * 删除文件
  262. * @param fileDir
  263. * @return
  264. */
  265. public boolean deleteExcel(){
  266. boolean flag = false;
  267. File file = new File(this.fileDir);
  268. // 判断目录或文件是否存在
  269. if (!file.exists()) { // 不存在返回 false
  270. return flag;
  271. } else {
  272. // 判断是否为文件
  273. if (file.isFile()) { // 为文件时调用删除文件方法
  274. file.delete();
  275. flag = true;
  276. }
  277. }
  278. return flag;
  279. }
  280. /**
  281. * 删除文件
  282. * @param fileDir
  283. * @return
  284. */
  285. public boolean deleteExcel(String path){
  286. boolean flag = false;
  287. File file = new File(path);
  288. // 判断目录或文件是否存在
  289. if (!file.exists()) { // 不存在返回 false
  290. return flag;
  291. } else {
  292. // 判断是否为文件
  293. if (file.isFile()) { // 为文件时调用删除文件方法
  294. file.delete();
  295. flag = true;
  296. }
  297. }
  298. return flag;
  299. }
  300. }
复制代码

测试如下:

实体bean:

  1. package com.myssm.util.poi;
  2. public class Man {
  3. private String name;
  4. private int sex;
  5. private String idCard;
  6. private float salary;
  7. public Man(String name, int sex, String idCard, float salary) {
  8. super();
  9. this.name = name;
  10. this.sex = sex;
  11. this.idCard = idCard;
  12. this.salary = salary;
  13. }
  14. public Man() {
  15. super();
  16. }
  17. public String getName() {
  18. return name;
  19. }
  20. public void setName(String name) {
  21. this.name = name;
  22. }
  23. public int getSex() {
  24. return sex;
  25. }
  26. public void setSex(int sex) {
  27. this.sex = sex;
  28. }
  29. public String getIdCard() {
  30. return idCard;
  31. }
  32. public void setIdCard(String idCard) {
  33. this.idCard = idCard;
  34. }
  35. public float getSalary() {
  36. return salary;
  37. }
  38. public void setSalary(float salary) {
  39. this.salary = salary;
  40. }
  41. }
复制代码
测试类:
  1. package com.myssm.util.poi;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. public class Test {
  5. public static void main(String[] args) {
  6. PoiExcelExport pee = new PoiExcelExport("E:/test.xls","sheet1");
  7. //数据
  8. List<Man> dataList = new ArrayList();
  9. Man man1 = new Man("张三",20,"男",(float)10000.8);
  10. Man man2 = new Man("李四",21,"男",(float)11000.8);
  11. Man man3 = new Man("王五",22,"女",(float)1200.8);
  12. Man man4 = new Man("赵六",23,"男",(float)13000.8);
  13. Man man5 = new Man("田七",24,"男",(float)14000.8);
  14. Man man6 = new Man();
  15. man6.setName("老八");
  16. dataList.add(man1);dataList.add(man2);dataList.add(man3);dataList.add(man4);dataList.add(man5);
  17. dataList.add(man6);
  18. //调用
  19. String titleColumn[] = {"name","sex","idCard","salary",""};
  20. String titleName[] = {"姓名","性别","身份证号","月薪","年薪"};
  21. int titleSize[] = {13,13,13,13,13};
  22. //其他设置 set方法可全不调用
  23. String colFormula[] = new String[5];
  24. colFormula[4] = "D@*12"; //设置第5列的公式
  25. pee.setColFormula(colFormula);
  26. pee.setAddress("A:D"); //自动筛选
  27. pee.wirteExcel(titleColumn, titleName, titleSize, dataList);
  28. }
  29. }
复制代码



最新评论

小黑屋|在路上 ( 蜀ICP备15035742号-1 

;

GMT+8, 2025-7-8 13:19

Copyright 2015-2025 djqfx

返回顶部