POI生成Excel文件:Excel,工具类,背景色,边框,居中,合并单元格

Stella981
• 阅读 379

背景今天分配到任务,要导出很多表格,懒得一个个写导出代码,故准备写个工具类

工具类代码如下:

  1 package com.swyx.tools.utils.poi;
  2 
  3 import java.io.File;
  4 import java.io.FileOutputStream;
  5 import java.io.OutputStream;
  6 import java.util.List;
  7 import java.util.Map;
  8 
  9 import org.apache.poi.hssf.usermodel.HSSFCell;
 10 import org.apache.poi.hssf.usermodel.HSSFCellStyle;
 11 import org.apache.poi.hssf.usermodel.HSSFPalette;
 12 import org.apache.poi.hssf.usermodel.HSSFRow;
 13 import org.apache.poi.hssf.usermodel.HSSFSheet;
 14 import org.apache.poi.hssf.usermodel.HSSFWorkbook;
 15 import org.apache.poi.ss.usermodel.BorderStyle;
 16 import org.apache.poi.ss.usermodel.FillPatternType;
 17 import org.apache.poi.ss.usermodel.HorizontalAlignment;
 18 import org.apache.poi.ss.util.CellRangeAddress;
 19 import org.apache.poi.ss.util.RegionUtil;
 20 
 21 /**
 22  * 
 23  * @author wangbaojun1992@163.com
 24  * @version poi version : 4.1.0
 25  */
 26 public class ExcelWriteUtil {
 27     
 28     /**
 29      * 
 30      * @param titleMape 标题行,为第一行标题内容与样式,参数Map<String,String>结构,字段如下:
 31      *         {
 32      *             value:内容值
 33      *             backgroundColor:背景色,为RGB颜色,3个色值以","隔开,默认"189,215,238"
 34      *         }
 35      * @param titleList 表头行,为第二行表头内容与样式,参数List<Map<String,String>>结构,字段如下:
 36      *         [
 37      *             {
 38      *                 value:内容值
 39      *                 backgroundColor:背景色,为RGB颜色,3个色值以","隔开,默认"189,215,238"
 40      *             }
 41      *         ]
 42      * @param contentList 内容,所有取值均被转换位String类型,参数List<List<String>>结构。
 43      * @param contentStyle 内容样式,参数为Map<String,String>结构,字段如下:
 44      *         {
 45      *             isZebra:内容区是否使用斑马线,枚举值:0是,1否,默认0
 46      *             zebraColor:斑马线颜色,为RGB颜色,3个色值以","隔开,默认"230,230,230"
 47      * @param dirName 缓存文件的文件夹的绝对路径
 48      * @param fileName 文件名,不要带后缀
 49      * @return
 50      * @throws Exception 
 51      */
 52     @SuppressWarnings("deprecation")
 53     public static String exportXlsExcel(Map<String, String> titleMape,List<Map<String, String>> titleList,List<List<String>> contentList,Map<String, String> contentStyle,String dirName,String fileName) throws Exception {
 54         //1.验证文件和文件夹名并创建Excel文件
 55         if(fileName == null || fileName.trim().equals("")) {
 56             throw new Exception("生成Excel文件异常:传入的文件名fileName不可为null、空字符串");
 57         }
 58         File parentDir = null;
 59         if(dirName == null || dirName.trim().equals("")) {
 60             throw new Exception("生成Excel文件异常:传入的文件夹名dirName不可为null、空字符串");
 61         }
 62         try {
 63             parentDir = new File(dirName);
 64             if(!parentDir.exists()) {
 65                 parentDir.mkdirs();
 66             }
 67         } catch (Exception e) {
 68             throw new Exception("生成Excel文件异常:传入的文件夹名dirName有误,dirName="+dirName);
 69         }finally {
 70             if(parentDir == null) {
 71                 throw new Exception("生成Excel文件异常:创建文件夹出错,dirName="+dirName);
 72             }
 73         }
 74         File excelFile = null;
 75         try {
 76             excelFile = new File(parentDir, fileName+".xls");
 77             if(excelFile.exists()) {
 78                 excelFile.delete();
 79             }
 80             excelFile.createNewFile();
 81         } catch (Exception e) {
 82             throw new Exception("生成Excel文件异常:生成File文件出错,fileName="+fileName);
 83         }finally {
 84             if(excelFile == null) {
 85                 throw new Exception("生成Excel文件异常:生成File文件出错,fileName="+fileName); 
 86             }
 87         }
 88         
 89         //2创建工作簿
 90         HSSFWorkbook wb=new HSSFWorkbook();
 91         HSSFSheet sheet=wb.createSheet();
 92         
 93         //3编辑标题
 94         //3.1标题样式
 95         HSSFCellStyle titleStyle=wb.createCellStyle();
 96         //3.1.1标题背景色
 97         HSSFPalette palette0_0 = wb.getCustomPalette();
 98         String backgroundColorStr0_0 = titleMape.get("backgroundColor");
 99         if(backgroundColorStr0_0 == null || backgroundColorStr0_0.trim().equals("")) {
100             backgroundColorStr0_0 = "189,215,238";
101         }
102         String[] backGroundColorStr0_0Strs = backgroundColorStr0_0.split(",");
103         if(backGroundColorStr0_0Strs.length != 3) {
104             backGroundColorStr0_0Strs = "189,215,238".split(",");
105         }
106         palette0_0.setColorAtIndex((short)9 ,(byte)new Integer(backGroundColorStr0_0Strs[0]).intValue(),(byte)(new Integer(backGroundColorStr0_0Strs[1]).intValue()),(byte)(new Integer(backGroundColorStr0_0Strs[2]).intValue()));
107         titleStyle.setFillForegroundColor((short)9 );
108         titleStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
109         //3.1.2标题合并单元格
110         // Region region1 = new Region(0, (short) 0, 0, (short) 6);//参数1:行号 参数2:起始列号 参数3:行号 参数4:终止列号 
111         CellRangeAddress rg0_0 = new CellRangeAddress(0,0,(short)0,(short)titleList.size()-1);
112         sheet.addMergedRegion(rg0_0);
113         //3.1.3标题边框
114         //TODO 此处合并单元格的边框样式没有生效,网络上一大堆复制黏贴的东西,试了很多未成功,头痛,暂时遗留该问题
115         //使用RegionUtil类为合并后的单元格添加边框
116         RegionUtil.setBorderBottom(BorderStyle.THIN, rg0_0, sheet); // 下边框
117         RegionUtil.setBorderLeft(BorderStyle.THIN, rg0_0, sheet); // 左边框
118         RegionUtil.setBorderRight(BorderStyle.THIN, rg0_0, sheet); // 有边框
119         RegionUtil.setBorderTop(BorderStyle.THIN, rg0_0, sheet); // 上边框
120         //3.1.4对齐
121         titleStyle.setAlignment(HorizontalAlignment.CENTER); //居中   
122        
123         //3.2写入标题
124         HSSFRow row0 = sheet.createRow(0);
125         HSSFCell cell0_0 = row0.createCell(0);
126         cell0_0.setCellValue(titleMape.get("value"));
127         cell0_0.setCellStyle(titleStyle);
128         
129         //4编辑表头
130         short fi = 11;
131         HSSFRow row1 = sheet.createRow(1);
132         for(int i = 0;i < titleList.size();i ++,fi++) {
133             Map<String, String> oneTitle = titleList.get(i);
134             //4.1当前列表头样式
135             HSSFCellStyle titleStyleI = wb.createCellStyle();
136             //4.1.1当前列表头背景色
137             HSSFPalette palette1_I = wb.getCustomPalette();
138             String backGroundColor1_I = oneTitle.get("backgroundColor");
139             if(backGroundColor1_I == null || backGroundColor1_I.trim().equals("")) {
140                 backGroundColor1_I = "189,215,238";
141             }
142             String[] backGroundColor1_IStrs = backGroundColor1_I.split(",");
143             if(backGroundColor1_IStrs.length != 3) {
144                 backGroundColor1_IStrs = "189,215,238".split(",");
145             }
146             palette1_I.setColorAtIndex(fi,(byte)(new Integer(backGroundColor1_IStrs[0]).intValue()),(byte)(new Integer(backGroundColor1_IStrs[1]).intValue()),(byte)(new Integer(backGroundColor1_IStrs[2]).intValue()));
147             titleStyleI.setFillPattern(FillPatternType.SOLID_FOREGROUND);
148             titleStyleI.setFillForegroundColor(fi);
149             //4.1.2当前列表头边框
150             titleStyleI.setBorderBottom(BorderStyle.THIN); //下边框
151             titleStyleI.setBorderLeft(BorderStyle.THIN);//左边框
152             titleStyleI.setBorderTop(BorderStyle.THIN);//上边框
153             titleStyleI.setBorderRight(BorderStyle.THIN);//右边框
154             //4.1.3对齐
155             titleStyleI.setAlignment(HorizontalAlignment.CENTER); //居中   
156             //4.2写入当前列表头
157             HSSFCell cell1_I = row1.createCell(i);
158             cell1_I.setCellValue(oneTitle.get("value"));
159             cell1_I.setCellStyle(titleStyleI);
160         }
161         
162         //5编辑内容区
163         //5.1准备样式
164         String isZebraStr = contentStyle.get("isZebra");
165         boolean isZebra = true;
166         if(isZebraStr != null && isZebraStr.equals("1")) {
167             isZebra = false;
168         }
169         //5.1.1斑马线行样式
170         HSSFCellStyle style1 = wb.createCellStyle();
171         //背景色
172         HSSFPalette paletteC = wb.getCustomPalette();
173         String backGroundColorC = contentStyle.get("zebraColor");
174         if(backGroundColorC == null || backGroundColorC.trim().equals("")) {
175             backGroundColorC = "230,230,230";
176         }
177         String[] backGroundColorCStrs = backGroundColorC.split(",");
178         if(backGroundColorCStrs.length != 3) {
179             backGroundColorCStrs = "230,230,230".split(",");
180         }
181         paletteC.setColorAtIndex((short)10 ,  (byte)(new Integer(backGroundColorCStrs[0]).intValue()),(byte)(new Integer(backGroundColorCStrs[1]).intValue()),(byte)(new Integer(backGroundColorCStrs[2]).intValue()));
182         style1.setFillPattern(FillPatternType.SOLID_FOREGROUND);
183         style1.setFillForegroundColor((short)10);
184         //边框
185         style1.setBorderBottom(BorderStyle.THIN); //下边框
186         style1.setBorderLeft(BorderStyle.THIN);//左边框
187         style1.setBorderTop(BorderStyle.THIN);//上边框
188         style1.setBorderRight(BorderStyle.THIN);//右边框
189         //5.1.2非斑马线行样式
190         HSSFCellStyle style0 = wb.createCellStyle();
191         //背景色
192         style0.setFillPattern(FillPatternType.SOLID_FOREGROUND);
193         //边框
194         style0.setBorderBottom(BorderStyle.THIN); //下边框
195         style0.setBorderLeft(BorderStyle.THIN);//左边框
196         style0.setBorderTop(BorderStyle.THIN);//上边框
197         style0.setBorderRight(BorderStyle.THIN);//右边框
198         
199         //5.2写入内容
200         for(int i = 0;i < contentList.size();i ++) {
201             List<String> contents = contentList.get(i);
202             HSSFRow rowI = sheet.createRow(i+2);
203             for(int j = 0;j < contents.size();j ++) {
204                 HSSFCell cellJ = rowI.createCell(j);
205                 cellJ.setCellValue(contents.get(j));
206                 if(i % 2 == 1) {
207                     if(isZebra) {
208                         cellJ.setCellStyle(style1);
209                     }else {
210                         cellJ.setCellStyle(style0);
211                     }
212                 }else {
213                     cellJ.setCellStyle(style0);
214                 }
215             }
216         }
217 
218         //6将文件输出
219         OutputStream ouputStream = null;
220         try {
221              ouputStream = new FileOutputStream(excelFile);
222              wb.write(ouputStream);
223              ouputStream.flush();
224              wb.close();
225         } catch (Exception e) {
226             throw new Exception("生成Excel文件异常:写出Excel文件异常"); 
227         }finally {
228             try {
229                 if(ouputStream != null) {
230                     ouputStream.close();
231                 }
232             } catch (Exception e2) {
233             }
234         }
235         
236         return excelFile.getAbsolutePath();
237     }
238 }

工具类调用:

 1 package com.swyx.tools.utils.poi;
 2 
 3 import java.util.ArrayList;
 4 import java.util.HashMap;
 5 import java.util.List;
 6 import java.util.Map;
 7 
 8 public class ExcelWriteUtilTest {
 9     public static void main(String[] args) throws Exception {
10         exportXlsExcel_Test();
11     }
12 
13     private static void exportXlsExcel_Test() throws Exception {
14         Map<String, String> titleMape = new HashMap<String, String>();
15         titleMape.put("value", "生成Excel文件测试");
16         
17         List<Map<String, String>> titleList = new ArrayList<Map<String,String>>();
18         Map<String, String> tm1 = new HashMap<String, String>();
19         tm1.put("value", "第1列");
20         titleList.add(tm1);
21         Map<String, String> tm2 = new HashMap<String, String>();
22         tm2.put("value", "第2列");
23         titleList.add(tm2);
24         Map<String, String> tm3 = new HashMap<String, String>();
25         tm3.put("value", "第3列");
26         titleList.add(tm3);
27         Map<String, String> tm4 = new HashMap<String, String>();
28         tm4.put("value", "第4列");
29         titleList.add(tm4);
30         Map<String, String> tm5 = new HashMap<String, String>();
31         tm5.put("value", "第5列");
32         titleList.add(tm5);
33         Map<String, String> tm6 = new HashMap<String, String>();
34         tm6.put("value", "第6列");
35         titleList.add(tm6);
36         
37         List<List<String>> contentList = new ArrayList<List<String>>();
38         List<String> cl1 = new ArrayList<String>();
39         cl1.add("111111");cl1.add("111111");cl1.add("111111");cl1.add("111111");cl1.add("111111");cl1.add("111111");
40         contentList.add(cl1);
41         
42         List<String> cl2 = new ArrayList<String>();
43         cl2.add("222222");cl2.add("222222");cl2.add("222222");cl2.add("222222");cl2.add("222222");cl2.add("222222");
44         contentList.add(cl2);
45         
46         List<String> cl3 = new ArrayList<String>();
47         cl3.add("333333");cl3.add("333333");cl3.add("333333");cl3.add("333333");cl3.add("333333");cl3.add("333333");
48         contentList.add(cl3);
49         
50         List<String> cl4 = new ArrayList<String>();
51         cl4.add("444444");cl4.add("444444");cl4.add("444444");cl4.add("444444");cl4.add("444444");cl4.add("444444");
52         contentList.add(cl4);
53         
54         List<String> cl5 = new ArrayList<String>();
55         cl5.add("555555");cl5.add("555555");cl5.add("555555");cl5.add("555555");cl5.add("555555");cl5.add("555555");
56         contentList.add(cl5);
57         
58         List<String> cl6 = new ArrayList<String>();
59         cl6.add("666666");cl6.add("666666");cl6.add("666666");cl6.add("666666");cl6.add("666666");cl6.add("666666");
60         contentList.add(cl6);
61         
62         List<String> cl7 = new ArrayList<String>();
63         cl7.add("777777");cl7.add("777777");cl7.add("777777");cl7.add("777777");cl7.add("777777");cl7.add("777777");
64         contentList.add(cl7);
65         
66         List<String> cl8 = new ArrayList<String>();
67         cl8.add("888888");cl8.add("888888");cl8.add("888888");cl8.add("888888");cl8.add("888888");cl8.add("888888");
68         contentList.add(cl8);
69         
70         List<String> cl9 = new ArrayList<String>();
71         cl9.add("999999");cl9.add("999999");cl9.add("999999");cl9.add("999999");cl9.add("999999");cl9.add("999999");
72         contentList.add(cl9);
73         
74         Map<String, String> contentStyle = new HashMap<String, String>();
75         String dirName = "C:\\WorkSpaces\\dxc";
76         String fileName = "ExcelWriteUtil_exportXlsExcel_Test";
77         
78         String name = ExcelWriteUtil.exportXlsExcel(titleMape, titleList, contentList, contentStyle, dirName, fileName);
79         System.out.println(name);
80     }
81 }

生成Excel:

POI生成Excel文件:Excel,工具类,背景色,边框,居中,合并单元格

点赞
收藏
评论区
推荐文章
blmius blmius
2年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Easter79 Easter79
2年前
swap空间的增减方法
(1)增大swap空间去激活swap交换区:swapoff v /dev/vg00/lvswap扩展交换lv:lvextend L 10G /dev/vg00/lvswap重新生成swap交换区:mkswap /dev/vg00/lvswap激活新生成的交换区:swapon v /dev/vg00/lvswap
Jacquelyn38 Jacquelyn38
2年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
Wesley13 Wesley13
2年前
Java获得今日零时零分零秒的时间(Date型)
publicDatezeroTime()throwsParseException{    DatetimenewDate();    SimpleDateFormatsimpnewSimpleDateFormat("yyyyMMdd00:00:00");    SimpleDateFormatsimp2newS
Wesley13 Wesley13
2年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Wesley13 Wesley13
2年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Stella981 Stella981
2年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Wesley13 Wesley13
2年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
3个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这