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

POI⽣成Excel⽂件:Excel,⼯具类,背景⾊,边框,居中,合并单元格背景今天分配到任务,要导出很多表格,懒得⼀个个写导出代码,故准备写个⼯具类⼯具类代码如下:1 package com.swyx.tools.utils.poi;23 import java.io.File;4 import java.io.FileOutputStream;5 import java.io.OutputStream;6 import java.util.List;7 import java.util.Map;89 import ermodel.HSSFCell;10 import ermodel.HSSFCellStyle;11 import ermodel.HSSFPalette;12 import ermodel.HSSFRow;13 import ermodel.HSSFSheet;14 import ermodel.HSSFWorkbook;15 import ermodel.BorderStyle;16 import ermodel.FillPatternType;17 import ermodel.HorizontalAlignment;18 import org.apache.poi.ss.util.CellRangeAddress;19 import org.apache.poi.ss.util.RegionUtil;2021 /**22 *23 * @author wangbaojun1992@24 * @version poi version : 4.1.025 */26 public class ExcelWriteUtil {2728 /**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>>结构。
java poi生成excel筛选条件

java poi生成excel筛选条件Java POI生成Excel筛选条件在日常开发中,常常会遇到需要将数据导出为Excel文件的需求。
而使用Java的POI库可以方便地实现这一功能。
本文将通过一步一步的示例,介绍如何使用Java POI生成Excel筛选条件。
下面我们将详细阐述这一过程。
第一步:导入所需的依赖库在使用Java POI库之前,首先要在项目中导入所需的依赖库。
可以通过Maven等构建工具将POI库添加到项目依赖中。
在pom.xml文件中添加以下依赖:<dependencies><dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>4.1.2</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>4.1.2</version></dependency></dependencies>第二步:创建工作簿和工作表在生成Excel文件之前,需要创建一个工作簿(Workbook)和一个工作表(Sheet)。
可以使用`XSSFWorkbook`类创建一个新的工作簿,使用`createSheet`方法创建一个新的工作表。
下面是示例代码:创建工作簿Workbook workbook = new XSSFWorkbook();创建工作表Sheet sheet = workbook.createSheet("Sheet1");第三步:创建数据行和列在工作表中,数据是以行和列的形式组织的。
《Java常用工具包大全》

《Java常用工具包大全》Java常用工具包大全Java发展至今已经有20多年的历史,而作为一个开源的编程语言,越来越多的工具包被开发出来,为我们的开发工作提供了便利和效率。
下面是Java常用工具包大全,包括了Java开发过程中最常用的各类工具包及其功能特性、使用场景和注意事项等。
一、Apache工具包Apache是世界著名的非营利组织,其旗下的工具包非常适合Java开发者使用。
除此之外,Apache还提供了广泛的文档和示例供开发者参考学习。
1. Apache CommonsApache Commons是Apache组织提供的一系列开源Java库和框架。
它包含了数十个组件,涉及了文件上传、线程池、日期转换、加密解密、JSON解析等方面。
使用场景:Apache Commons中的每个组件都有助于快速实现复杂的应用程序,针对每一种拓展都能够省去自己编写的时间和精力。
2. Apache POIApache POI是Apache组织推出的一个用于读写Excel的工具包。
POI是“Poor Obfuscation Implementation”的缩写,是一款很好的操作Excel 文件的开源类库。
使用场景:在Java应用程序中读取或者写入Excel文档或者其他Office 文档的时候,使用Apache POI是一个不错的选择。
3. Log4jLog4j是Apache组织提供的一种可扩展的日志系统。
可以对日志记录进行详细的控制,譬如记录级别、输出到文件或者控制台等。
使用场景:通过Log4j记录详细的日志,可在排查问题时帮助开发人员快速找到问题所在。
4. VelocityVelocity是一种模板引擎,它通过将动态内容组合到模板中来生成输出。
在开发Java应用程序时,使用Velocity能够轻松生成格式一致的输出。
使用场景:在Java程序中处理动态内容和输出时,使用Velocity是一个很不错的选择。
二、Spring工具包Spring是目前Java领域最流行的应用程序开发框架。
Java使用Poi-tlword模板导出word

Java使⽤Poi-tlword模板导出word 1.导⼊依赖<dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>4.1.2</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml-schemas</artifactId><version>4.1.2</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>4.1.2</version></dependency><dependency><groupId>com.deepoove</groupId><artifactId>poi-tl</artifactId><version>1.7.3</version></dependency>2.新建⼀个word,制作导出模板模板放⼊ resource/static/word/template⽂件夹下3.编写⼯具类⼯具类--WordExportServer.javapublic class WordExportServer {/*** 导出word**/public static void export(WordExportData wordExportData) throws IOException {HttpServletResponse response=wordExportData.getResponse();OutputStream out = response.getOutputStream();;XWPFTemplate template =null;try{ClassPathResource classPathResource = new ClassPathResource(wordExportData.getTemplateDocPath());String resource = classPathResource.getURL().getPath();resource= PdfUtil1.handleFontPath(resource);//渲染表格HackLoopTableRenderPolicy policy = new HackLoopTableRenderPolicy();Configure config = Configure.newBuilder().bind(wordExportData.getTableDataField(), policy).build();template = pile(resource, config).render(wordExportData.getWordData());String fileName=getFileName(wordExportData);/** ===============⽣成word到设置浏览默认下载地址=============== **/// 设置强制下载不打开response.setContentType("application/force-download");// 设置⽂件名response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);template.write(out);}catch (Exception e){e.printStackTrace();}finally {out.flush();out.close();template.close();}}/*** 获取导出下载的word名称* @param wordExportData* @return ng.String**/public static String getFileName(WordExportData wordExportData){if(null !=wordExportData.getFileName()){return wordExportData.getFileName()+".docx";}return System.currentTimeMillis()+".docx";}}word数据包装类--WordExportData .java@Datapublic class WordExportData {/*** word模板路径(static/wordTemplate/dealerListDocTemplate.docx)**/private String templateDocPath;/*** word填充数据(key值与模板中的key值要保持⼀致)**/private Map<String,Object> wordData;/*** word表格数据key值**/private String tableDataField;/*** word导出后的⽂件名(不填则⽤当前时间代替)**/private String fileName;private HttpServletResponse response;}4.controller层调⽤@RequestMapping("/printWord")public void printWord(HttpServletRequest request, HttpServletResponse response) throws IOException{String[] ids=request.getParameter("ids").split(";");List<DealerDto> goodsDataList=goodsService.getDealerListByIds(ids);Map<String,Object> docData=new HashMap<>(3);docData.put("detailList",goodsDataList);docData.put("title",标题);docData.put("subTitle",副标题);WordExportData wordExportData=new WordExportData();wordExportData.setResponse(response);wordExportData.setTableDataField("detailList");wordExportData.setTemplateDocPath(DEALER_DOC_TEMPLATE_PATH);//副本存放路径wordExportData.setWordData(docData);WordExportServer.export(wordExportData);}5.前端调⽤var ids = [];for (var index in checkData) {ids.push(checkData[index].id);}var batchIds = ids.join(";");layer.confirm('确定下载选中的数据吗?', function (index) {layer.close(index);window.location.href ='/goods/printWord?ids=' + batchIds;});6.总结优点:使⽤⽅法很简单,使⽤⼯具类的⽅法,⽅便复⽤于其他模块。
JavaPOI操作word文档内容、表格

JavaPOI操作word⽂档内容、表格⼀、pom<dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>4.0.0</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-scratchpad</artifactId><version>4.0.0</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>4.0.0</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml-schemas</artifactId><version>4.0.0</version></dependency>⼆、直接上代码word模板中${content} 注意我只有在.docx⽤XWPFDocument才有效2.1/*** 获取document**/XWPFDocument document = null;try {document = new XWPFDocument(inputStream);} catch (IOException ioException) {ioException.printStackTrace();}/*** 替换段落⾥⾯的变量** @param doc 要替换的⽂档* @param params 参数*/private void replaceInPara(XWPFDocument doc, Map<String, String> params) {for (XWPFParagraph para : doc.getParagraphs()) {replaceInPara(para, params);}}/*** 替换段落⾥⾯的变量** @param para 要替换的段落* @param params 参数*/private void replaceInPara(XWPFParagraph para, Map<String, String> params) {List<XWPFRun> runs;Matcher matcher;replaceText(para);//如果para拆分的不对,则⽤这个⽅法修改成正确的if (matcher(para.getParagraphText()).find()) {runs = para.getRuns();for (int i = 0; i < runs.size(); i++) {XWPFRun run = runs.get(i);String runText = run.toString();matcher = matcher(runText);if (matcher.find()) {while ((matcher = matcher(runText)).find()) {runText = matcher.replaceFirst(String.valueOf(params.get(matcher.group(1))));}//直接调⽤XWPFRun的setText()⽅法设置⽂本时,在底层会重新创建⼀个XWPFRun,把⽂本附加在当前⽂本后⾯, para.removeRun(i);para.insertNewRun(i).setText(runText);}}}}/*** 替换⽂本内容* @param para* @return*/private List<XWPFRun> replaceText(XWPFParagraph para) {List<XWPFRun> runs = para.getRuns();String str = "";boolean flag = false;for (int i = 0; i < runs.size(); i++) {XWPFRun run = runs.get(i);String runText = run.toString();if (flag || runText.equals("${")) {str = str + runText;flag = true;para.removeRun(i);if (runText.equals("}")) {flag = false;para.insertNewRun(i).setText(str);str = "";}i--;}}return runs;}2.22.2.1XWPFTable table = document.getTableArray(0);//获取当前表格XWPFTableRow twoRow = table.getRow(2);//获取某⼀⾏XWPFTableRow nextRow = table.insertNewTableRow(3);//插⼊⼀⾏XWPFTableCell firstRowCellOne = firstRow.getCell(0);firstRowCellOne.removeParagraph(0);//删除默认段落,要不然表格内第⼀条为空⾏XWPFParagraph pIO2 =firstRowCellOne.addParagraph();XWPFRun rIO2 = pIO2.createRun();rIO2.setFontFamily("宋体");//字体rIO2.setFontSize(8);//字体⼤⼩rIO2.setBold(true);//是否加粗rIO2.setColor("FF0000");//字体颜⾊rIO2.setText("这是写⼊的内容");//rIO2.addBreak(BreakType.TEXT_WRAPPING);//软换⾏,亲测有效/*** 复制单元格和样式** @param targetRow 要复制的⾏* @param sourceRow 被复制的⾏*/public void createCellsAndCopyStyles(XWPFTableRow targetRow, XWPFTableRow sourceRow) {targetRow.getCtRow().setTrPr(sourceRow.getCtRow().getTrPr());List<XWPFTableCell> tableCells = sourceRow.getTableCells();if (CollectionUtils.isEmpty(tableCells)) {return;}for (XWPFTableCell sourceCell : tableCells) {XWPFTableCell newCell = targetRow.addNewTableCell();newCell.getCTTc().setTcPr(sourceCell.getCTTc().getTcPr());List sourceParagraphs = sourceCell.getParagraphs();if (CollectionUtils.isEmpty(sourceParagraphs)) {continue;}XWPFParagraph sourceParagraph = (XWPFParagraph) sourceParagraphs.get(0);List targetParagraphs = newCell.getParagraphs();if (CollectionUtils.isEmpty(targetParagraphs)) {XWPFParagraph p = newCell.addParagraph();p.getCTP().setPPr(sourceParagraph.getCTP().getPPr());XWPFRun run = p.getRuns().isEmpty() ? p.createRun() : p.getRuns().get(0);run.setFontFamily(sourceParagraph.getRuns().get(0).getFontFamily());} else {XWPFParagraph p = (XWPFParagraph) targetParagraphs.get(0);p.getCTP().setPPr(sourceParagraph.getCTP().getPPr());XWPFRun run = p.getRuns().isEmpty() ? p.createRun() : p.getRuns().get(0);if (sourceParagraph.getRuns().size() > 0) {run.setFontFamily(sourceParagraph.getRuns().get(0).getFontFamily());}}}}#### 2.2.3/*** 合并单元格** @param table 表格对象* @param beginRowIndex 开始⾏索引* @param endRowIndex 结束⾏索引* @param colIndex 合并列索引*/public void mergeCell(XWPFTable table, int beginRowIndex, int endRowIndex, int colIndex) { if (beginRowIndex == endRowIndex || beginRowIndex > endRowIndex) {return;}//合并⾏单元格的第⼀个单元格CTVMerge startMerge = CTVMerge.Factory.newInstance();startMerge.setVal(STMerge.RESTART);//合并⾏单元格的第⼀个单元格之后的单元格CTVMerge endMerge = CTVMerge.Factory.newInstance();endMerge.setVal(STMerge.CONTINUE);table.getRow(beginRowIndex).getCell(colIndex).getCTTc().getTcPr().setVMerge(startMerge); for (int i = beginRowIndex + 1; i <= endRowIndex; i++) {table.getRow(i).getCell(colIndex).getCTTc().getTcPr().setVMerge(endMerge);}}/*** insertRow 在word表格中指定位置插⼊⼀⾏,并将某⼀⾏的样式复制到新增⾏* @param copyrowIndex 需要复制的⾏位置* @param newrowIndex 需要新增⼀⾏的位置* */public static void insertRow(XWPFTable table, int copyrowIndex, int newrowIndex) {// 在表格中指定的位置新增⼀⾏XWPFTableRow targetRow = table.insertNewTableRow(newrowIndex);// 获取需要复制⾏对象XWPFTableRow copyRow = table.getRow(copyrowIndex);//复制⾏对象targetRow.getCtRow().setTrPr(copyRow.getCtRow().getTrPr());//或许需要复制的⾏的列List<XWPFTableCell> copyCells = copyRow.getTableCells();//复制列对象XWPFTableCell targetCell = null;for (int i = 0; i < copyCells.size(); i++) {XWPFTableCell copyCell = copyCells.get(i);targetCell = targetRow.addNewTableCell();targetCell.getCTTc().setTcPr(copyCell.getCTTc().getTcPr());if (copyCell.getParagraphs() != null && copyCell.getParagraphs().size() > 0) {targetCell.getParagraphs().get(0).getCTP().setPPr(copyCell.getParagraphs().get(0).getCTP().getPPr()); if (copyCell.getParagraphs().get(0).getRuns() != null&& copyCell.getParagraphs().get(0).getRuns().size() > 0) {XWPFRun cellR = targetCell.getParagraphs().get(0).createRun();cellR.setBold(copyCell.getParagraphs().get(0).getRuns().get(0).isBold());}}}}/*** 正则匹配字符串** @param str* @return*/private Matcher matcher(String str) {Pattern pattern = pile("\\$\\{(.+?)\\}", Pattern.CASE_INSENSITIVE);Matcher matcher = pattern.matcher(str);return matcher;}。
【POI】hutool万能工具的poi使用(Excel操作)

【POI】hutool万能⼯具的poi使⽤(Excel操作)POI技术(hutool⼯具的简单使⽤)POI: java技术,操作excel⽂档hutool-excel:常⽤poi功能,简化封装成⼯具类写出⽂档数据:(1)导出数据报表①获得能够向excel表格中输出信息对象[流]writer = ExcelUtil.getWriter("⽂件路径");注释:excel表格⽂件标准后缀:*.xls、*.xlsx② excel表格数据包含:表头:指明当前列数据的含义每⾏:多个单元格的数据;List<Object> | Map<字符串标题,Object>表格:多⾏数据。
List<Map<表头,Object数据>>③将数据写出到Excel⽂档:writer.write(list);④关闭流:writer.close();(2)向输出流中写⼊数据①创建⼀个写出的⼯具:ExcelWriter ew = ExcelUtil.getWriter();②将list多⾏数据集合写⼊:writer.write(list);③ flush,将数据写⼊到指定输出流中:writer.flush(outputStream);④关闭流:writer.close();(3)设置表格的sheet的名字writer.renameSheet("xxx")读⼊⽂档数据:①创建⼀个读⼊的⼯具:ExcelReader reader = ExcelUtil.getReader("⽂件路径");②读取⾥⾯的数据:List<Map<String,Object>> list = reader.readAll();③关闭流:reader.close();实例代码:导出:准备:导⼊POI的jar以及hutool的jar①⽅式⼀:(表格信息写到对应的⽂件路径)ExcelUtil.getWriter("⽂件路径"); //直接写到⽂件⾥②⽅式⼆:(表格信息写到特定的输出流⾥)List<Person> list = new ArrayList<Person>();persons.add(new Person("1001", "黄浩", 1, 18, "233456789", "郑州"));persons.add(new Person("1002", "杨宁", 1, 18, "233456789", "郑州"));persons.add(new Person("1003", "洪诗鹏", 1, 18, "233456789", "郑州"));// 重要将数据转化为hutool-excel,能够直接写出的数据结构:List<Map<String,Object>>// 创建⼀个存储多⾏数据的listList<Map<String, Object>> persons = new ArrayList<Map<String, Object>>();for (Person person : list) {// 每个person信息,代表⼀⾏数据:Map<String,person的属性>Map<String, Object> map = new LinkedHashMap<String, Object>();map.put("编号", person.getId());map.put("名字", person.getName());map.put("年龄", person.getAge());map.put("地址", person.getAddress());persons.add(map); // 将当前⾏的数据,加⼊persons}ExcelWriter writer = ExcelUtil.getWriter("D:/person.xlsx");// ①创建写出数据到⽂档中的⼯具writer.renameSheet("联系⼈信息表"); //设置sheet的名字writer.write(persons); // ②将数据写出到⽂档导出⼯具中writer.flush(输出流);//输出流:可以是⽂件输出流,也可以是控制器的响应流进⾏下载writer.close(); // ③关闭流导⼊:①创建⼀个读⼊的⼯具:ExcelReader reader = ExcelUtil.getReader("D:/person.xlsx");②读取⾥⾯的数据:List<Map<String, Object>> list = reader.readAll();③关闭流:reader.close();。
Java使用poi做加自定义注解实现对象与Excel相互转换

Java使⽤poi做加⾃定义注解实现对象与Excel相互转换引⼊依赖maven<dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>3.17</version></dependency>Gradleimplementation group: 'org.apache.poi', name: 'poi', version: '3.17'代码展⽰1、⾃定义注解类@Retention(value = RetentionPolicy.RUNTIME)@Target(value = ElementType.FIELD)public @interface Excel {String name();//列的名字int width() default 6000;//列的宽度int index() default -1;//决定⽣成的顺序boolean isMust() default true; // 是否为必须值,默认是必须的}2、Java的Excel对象,只展现了field,get与set⽅法就忽略了public class GoodsExcelModel {@Excel(name = "ID_禁⽌改动", index = 0, width = 0)private Long picId;//picId@Excel(name = "产品ID_禁⽌改动", index = 1, width = 0)private Long productId;@Excel(name = "型号", index = 3)private String productName;//产品型号@Excel(name = "系列", index = 2)private String seriesName;//系列名字@Excel(name = "库存", index = 5)private Long quantity;@Excel(name = "属性值", index = 4)private String propValue;@Excel(name = "价格", index = 6)private Double price;@Excel(name = "商品编码", index = 7, isMust = false)private String outerId;@Id@GeneratedValue(strategy = GenerationType.IDENTITY)private Long dbId; // 数据库⾃增长idprivate Date createTime; // 记录创建时间}3、Excel表格与对象转换的⼯具类,使⽤时指定泛型参数和泛型的class即可public class ExcelUtil {private static final String GET = "get";private static final String SET = "set";private static Logger logger = LoggerFactory.getLogger(ExcelUtil.class);/*** 将对象转换成Excel** @param objList 需要转换的对象* @return 返回是poi中的对象*/public static HSSFWorkbook toExcel(List objList) {if (CollectionUtils.isEmpty(objList)) throw new NullPointerException("⽆效的数据");Class aClass = objList.get(0).getClass();Field[] fields = aClass.getDeclaredFields();HSSFWorkbook workbook = new HSSFWorkbook();HSSFSheet sheet = workbook.createSheet();for (int i = 0; i < objList.size(); i++) {HSSFRow row = sheet.createRow(i + 1);//要从第⼆⾏开始写HSSFRow topRow = null;if (i == 0) topRow = sheet.createRow(0);for (Field field : fields) {Excel excel = field.getAnnotation(Excel.class);//得到字段是否使⽤了Excel注解if (excel == null) continue;HSSFCell cell = row.createCell(excel.index());//设置当前值放到第⼏列String startName = field.getName().substring(0, 1);String endName = field.getName().substring(1, field.getName().length());String methodName = new StringBuffer(GET).append(startName.toUpperCase()).append(endName).toString();try {Method method = aClass.getMethod(methodName);//根据⽅法名获取⽅法,⽤于调⽤Object invoke = method.invoke(objList.get(i));if (invoke == null) continue;cell.setCellValue(invoke.toString());} catch (NoSuchMethodException e) {e.printStackTrace();} catch (IllegalAccessException e) {e.printStackTrace();} catch (InvocationTargetException e) {e.printStackTrace();}if (topRow == null) continue;HSSFCell topRowCell = topRow.createCell(excel.index());topRowCell.setCellValue(());sheet.setColumnWidth(excel.index(), excel.width());}}return workbook;}/*** 将Excel⽂件转换为指定对象** @param file 传⼊的Excel* @param c 需要被指定的class* @return* @throws IOException* @throws IllegalAccessException* @throws InstantiationException*/public static <T> List<T> excelFileToObject(MultipartFile file, Class<T> c) throws IOException, IllegalAccessException, InstantiationException { //key为反射得到的下标,value为对于的set⽅法Map<Integer, String> methodMap = new HashMap<>();//保存第⼀列的值与对应的下标,⽤于验证⽤户是否删除了该列,key为下标,value为名字Map<Integer, String> startRowNameMap = new HashMap<>();//⽤来记录当前参数是否为必须的Map<Integer, Boolean> fieldIsMustMap = new HashMap<>();//得到所有的字段Field[] fields = c.getDeclaredFields();for (Field field : fields) {Excel excel = field.getAnnotation(Excel.class);if (excel == null) continue;String startName = field.getName().substring(0, 1);String endName = field.getName().substring(1, field.getName().length());String methodName = new StringBuffer(SET).append(startName.toUpperCase()).append(endName).toString();methodMap.put(excel.index(), methodName);startRowNameMap.put(excel.index(), ());fieldIsMustMap.put(excel.index(), excel.isMust());}String fileName = file.getOriginalFilename();Workbook wb = fileName.endsWith(".xlsx") ? new XSSFWorkbook(file.getInputStream()) : new HSSFWorkbook(file.getInputStream());Sheet sheet = wb.getSheetAt(0);Row sheetRow = sheet.getRow(0);for (Cell cell : sheetRow) {Integer columnIndex = cell.getColumnIndex();if (cell.getCellTypeEnum() != CellType.STRING) throw new ExcelException("excel校验失败, 请勿删除⽂件中第⼀⾏数据 ");String value = cell.getStringCellValue();String name = startRowNameMap.get(columnIndex);if (name == null) throw new ExcelException("excel校验失败,请勿移动⽂件中任何列的顺序");if (!name.equals(value)) throw new ExcelException("excel校验失败,【" + name + "】列被删除,请勿删除⽂件中任何列 ");}sheet.removeRow(sheetRow);//第⼀⾏是不需要被反射赋值的List<T> models = new ArrayList<>();for (Row row : sheet) {if (row == null || !checkRow(row)) continue;T obj = c.newInstance();//创建新的实例化对象Class excelModelClass = obj.getClass();startRowNameMap.entrySet().forEach(x -> {Integer index = x.getKey();Cell cell = row.getCell(index);String methodName = methodMap.get(index);if (StringUtils.isEmpty(methodName)) return;List<Method> methods = Lists.newArrayList(excelModelClass.getMethods()).stream().filter(m -> m.getName().startsWith(SET)).collect(Collectors.toList());String rowName = startRowNameMap.get(index);//列的名字for (Method method : methods) {if (!method.getName().startsWith(methodName)) continue;//检测value属性String value = valueCheck(cell, rowName, fieldIsMustMap.get(index));//开始进⾏调⽤⽅法反射赋值methodInvokeHandler(obj, method, value);}});models.add(obj);}return models;}/*** 检测当前需要赋值的value** @param cell 当前循环⾏中的列对象* @param rowName 列的名字{@link Excel}中的name* @param isMust 是否为必须的* @return 值*/private static String valueCheck(Cell cell, String rowName, Boolean isMust) {//有时候删除单个数据会造成cell为空,也可能是value为空if (cell == null && isMust) {throw new ExcelException("excel校验失败,【" + rowName + "】中的数据禁⽌单个删除");}if (cell == null) return null;cell.setCellType(CellType.STRING);String value = cell.getStringCellValue();if ((value == null || value.trim().isEmpty()) && isMust) {throw new ExcelException("excel校验失败,【" + rowName + "】中的数据禁⽌单个删除");}return value;}/*** 反射赋值的处理的⽅法** @param obj 循环创建的需要赋值的对象* @param method 当前对象期中⼀个set⽅法* @param value 要被赋值的内容*/private static void methodInvokeHandler(Object obj, Method method, String value) {Class<?> parameterType = method.getParameterTypes()[0];try {if (parameterType == null) {method.invoke(obj);return;}String name = parameterType.getName();if (name.equals(String.class.getName())) {method.invoke(obj, value);return;}if (name.equals(Long.class.getName())) {method.invoke(obj, Long.valueOf(value));return;}if (name.equals(Double.class.getName())) {method.invoke(obj, Double.valueOf(value));}} catch (IllegalAccessException e) {e.printStackTrace();} catch (InvocationTargetException e) {e.printStackTrace();}}private static boolean checkRow(Row row) {try {if (row == null) return false;short firstCellNum = row.getFirstCellNum();short lastCellNum = row.getLastCellNum();if (firstCellNum < 0 && lastCellNum < 0) return false;if (firstCellNum != 0) {for (short i = firstCellNum; i < lastCellNum; i++) { Cell cell = row.getCell(i);String cellValue = cell.getStringCellValue(); if (!StringUtils.isBlank(cellValue)) return true; }return false;}return true;} catch (Exception e) {return true;}}4、导出Excel与导⼊Excel的⽰例代码使⽤展⽰1、选择数据2、设置基本数据,然后导出表格3、导出表格效果,在图⽚中看到A和B列没有显⽰出来,这是因为我将其宽度配置为了04、将必须参数删除后上传测试,如下图中,商品编码我设置isMust为false所以删除数据就不会出现此问题。
Java操作word文档使用JACOB和POI操作word,Excel,PPT需要的jar包

Java操作word⽂档使⽤JACOB和POI操作word,Excel,PPT需要的jar包可参考⽂档:下载jar包如上是jacob-1.17-M2.jar对应的jar包和dll⽂件....但是我在maven仓库中并没有发现jacob-1.17版本的.所以如果使⽤maven项⽬的话推荐下载jacob-1.14版本的jar包和dll⽂件.使⽤⽅式:import java.io.File;import java.io.FileInputStream;import java.util.ArrayList;import java.util.Arrays;import com.jacob.activeX.ActiveXComponent;public class WriteDoc2 {public static void main(String[] args) {//在正式批量跑之前,做单个word⽂档的测试.WordUtils util = new WordUtils(true);util.openDocument("C:\\Users\\ABC\\Desktop\\test.docx");util.setSaveOnExit(true);util.insertText("xxx444dddd4x");util.saveAs("C:\\Users\\ABC\\Desktop\\test.docx");util.closeDocument();}}对应WordUtils.java⼯具类,我是使⽤的如下:import com.jacob.activeX.ActiveXComponent;import .Dispatch;import .Variant;public class WordUtils {// word运⾏程序对象private ActiveXComponent word;// 所有word⽂档集合private Dispatch documents;// word⽂档private Dispatch doc;// 选定的范围或插⼊点private Dispatch selection;// 保存退出private boolean saveOnExit;public WordUtils(boolean visible) {word = new ActiveXComponent("Word.Application");word.setProperty("Visible", new Variant(visible));documents = word.getProperty("Documents").toDispatch();}/*** 设置退出时参数** @param saveOnExit* boolean true-退出时保存⽂件,false-退出时不保存⽂件 */public void setSaveOnExit(boolean saveOnExit) {this.saveOnExit = saveOnExit;}/*** 创建⼀个新的word⽂档*/public void createNewDocument() {doc = Dispatch.call(documents, "Add").toDispatch();selection = Dispatch.get(word, "Selection").toDispatch();}/*** 打开⼀个已经存在的word⽂档** @param docPath*/public void openDocument(String docPath) {doc = Dispatch.call(documents, "Open", docPath).toDispatch();selection = Dispatch.get(word, "Selection").toDispatch();}/*** 打开⼀个有密码保护的word⽂档* @param docPath* @param password*/public void openDocument(String docPath, String password) {doc = Dispatch.call(documents, "Open", docPath).toDispatch();unProtect(password);selection = Dispatch.get(word, "Selection").toDispatch();}/*** 去掉密码保护* @param password*/public void unProtect(String password){try{String protectionType = Dispatch.get(doc, "ProtectionType").toString();if(!"-1".equals(protectionType)){Dispatch.call(doc, "Unprotect", password);}}catch(Exception e){e.printStackTrace();}}/*** 添加密码保护* @param password*/public void protect(String password){String protectionType = Dispatch.get(doc, "ProtectionType").toString();if("-1".equals(protectionType)){Dispatch.call(doc, "Protect",new Object[]{new Variant(3), new Variant(true), password});}}/*** 显⽰审阅的最终状态*/public void showFinalState(){Dispatch.call(doc, "AcceptAllRevisionsShown");}/*** 打印预览:*/public void printpreview() {Dispatch.call(doc, "PrintPreView");}/*** 打印*/public void print(){Dispatch.call(doc, "PrintOut");}public void print(String printerName) {word.setProperty("ActivePrinter", new Variant(printerName));print();}/*** 指定打印机名称和打印输出⼯作名称* @param printerName* @param outputName*/public void print(String printerName, String outputName){word.setProperty("ActivePrinter", new Variant(printerName));Dispatch.call(doc, "PrintOut", new Variant[]{new Variant(false), new Variant(false), new Variant(0), new Variant(outputName)}); }/*** 把选定的内容或插⼊点向上移动** @param pos*/public void moveUp(int pos) {move("MoveUp", pos);}/*** 把选定的内容或者插⼊点向下移动** @param pos*/public void moveDown(int pos) {move("MoveDown", pos);}/*** 把选定的内容或者插⼊点向左移动** @param pos*/public void moveLeft(int pos) {move("MoveLeft", pos);}/*** 把选定的内容或者插⼊点向右移动** @param pos*/public void moveRight(int pos) {move("MoveRight", pos);}/*** 把选定的内容或者插⼊点向右移动*/public void moveRight() {Dispatch.call(getSelection(), "MoveRight");}/*** 把选定的内容或者插⼊点向指定的⽅向移动* @param actionName* @param pos*/private void move(String actionName, int pos) {for (int i = 0; i < pos; i++)Dispatch.call(getSelection(), actionName);}/*** 把插⼊点移动到⽂件⾸位置*/public void moveStart(){Dispatch.call(getSelection(), "HomeKey", new Variant(6));}/*** 把插⼊点移动到⽂件末尾位置*/public void moveEnd(){Dispatch.call(getSelection(), "EndKey", new Variant(6));}/*** 插⼊换页符*/public void newPage(){Dispatch.call(getSelection(), "InsertBreak");}public void nextPage(){moveEnd();moveDown(1);}public int getPageCount(){Dispatch selection = Dispatch.get(word, "Selection").toDispatch();return Dispatch.call(selection,"information", new Variant(4)).getInt(); }/*** 获取当前的选定的内容或者插⼊点* @return当前的选定的内容或者插⼊点*/public Dispatch getSelection(){if (selection == null)selection = Dispatch.get(word, "Selection").toDispatch();return selection;}/*** 从选定内容或插⼊点开始查找⽂本* @param findText 要查找的⽂本* @return boolean true-查找到并选中该⽂本,false-未查找到⽂本*/public boolean find(String findText){if(findText == null || findText.equals("")){return false;}// 从selection所在位置开始查询Dispatch find = Dispatch.call(getSelection(), "Find").toDispatch();// 设置要查找的内容Dispatch.put(find, "Text", findText);// 向前查找Dispatch.put(find, "Forward", "True");// 设置格式Dispatch.put(find, "Format", "True");// ⼤⼩写匹配Dispatch.put(find, "MatchCase", "True");// 全字匹配Dispatch.put(find, "MatchWholeWord", "True");// 查找并选中return Dispatch.call(find, "Execute").getBoolean();}/*** 查找并替换⽂字* @param findText* @param newText* @return boolean true-查找到并替换该⽂本,false-未查找到⽂本*/public boolean replaceText(String findText, String newText){moveStart();if (!find(findText))return false;Dispatch.put(getSelection(), "Text", newText);return true;}/*** 进⼊页眉视图*/public void headerView(){//取得活动窗体对象Dispatch ActiveWindow = word.getProperty( "ActiveWindow").toDispatch();//取得活动窗格对象Dispatch ActivePane = Dispatch.get(ActiveWindow, "ActivePane").toDispatch();//取得视窗对象Dispatch view = Dispatch.get(ActivePane, "View").toDispatch();Dispatch.put(view, "SeekView", "9");}/*** 进⼊页脚视图*/public void footerView(){//取得活动窗体对象Dispatch ActiveWindow = word.getProperty( "ActiveWindow").toDispatch();//取得活动窗格对象Dispatch ActivePane = Dispatch.get(ActiveWindow, "ActivePane").toDispatch();//取得视窗对象Dispatch view = Dispatch.get(ActivePane, "View").toDispatch();Dispatch.put(view, "SeekView", "10");}/*** 进⼊普通视图*/public void pageView(){//取得活动窗体对象Dispatch ActiveWindow = word.getProperty( "ActiveWindow").toDispatch();//取得活动窗格对象Dispatch ActivePane = Dispatch.get(ActiveWindow, "ActivePane").toDispatch();//取得视窗对象Dispatch view = Dispatch.get(ActivePane, "View").toDispatch();Dispatch.put(view, "SeekView", new Variant(0));//普通视图}/*** 全局替换⽂本* @param findText* @param newText*/public void replaceAllText(String findText, String newText){int count = getPageCount();for(int i = 0; i < count; i++){headerView();while (find(findText)){Dispatch.put(getSelection(), "Text", newText);moveEnd();}footerView();while (find(findText)){Dispatch.put(getSelection(), "Text", newText);moveStart();}pageView();moveStart();while (find(findText)){Dispatch.put(getSelection(), "Text", newText);moveStart();}nextPage();}}/*** 全局替换⽂本* @param findText* @param newText*/public void replaceAllText(String findText, String newText, String fontName, int size){ /****插⼊页眉页脚*****///取得活动窗体对象Dispatch ActiveWindow = word.getProperty( "ActiveWindow").toDispatch();//取得活动窗格对象Dispatch ActivePane = Dispatch.get(ActiveWindow, "ActivePane").toDispatch();//取得视窗对象Dispatch view = Dispatch.get(ActivePane, "View").toDispatch();/****设置页眉*****/Dispatch.put(view, "SeekView", "9");while (find(findText)){Dispatch.put(getSelection(), "Text", newText);moveStart();}/****设置页脚*****/Dispatch.put(view, "SeekView", "10");while (find(findText)){Dispatch.put(getSelection(), "Text", newText);moveStart();}Dispatch.put(view, "SeekView", new Variant(0));//恢复视图moveStart();while (find(findText)){Dispatch.put(getSelection(), "Text", newText);putFontSize(getSelection(), fontName, size);moveStart();}}/*** 设置选中或当前插⼊点的字体* @param selection* @param fontName* @param size*/public void putFontSize(Dispatch selection, String fontName, int size){Dispatch font = Dispatch.get(selection, "Font").toDispatch();Dispatch.put(font, "Name", new Variant(fontName));Dispatch.put(font, "Size", new Variant(size));}/*** 在当前插⼊点插⼊字符串*/public void insertText(String text){Dispatch.put(getSelection(), "Text", text);}/*** 将指定的⽂本替换成图⽚* @param findText* @param imagePath* @return boolean true-查找到并替换该⽂本,false-未查找到⽂本*/public boolean replaceImage(String findText, String imagePath, int width, int height){moveStart();if (!find(findText))return false;Dispatch picture = Dispatch.call(Dispatch.get(getSelection(), "InLineShapes").toDispatch(), "AddPicture", imagePath).toDispatch(); Dispatch.call(picture, "Select");Dispatch.put(picture, "Width", new Variant(width));Dispatch.put(picture, "Height", new Variant(height));moveRight();return true;}/*** 全局将指定的⽂本替换成图⽚* @param findText* @param imagePath*/public void replaceAllImage(String findText, String imagePath, int width, int height){moveStart();while (find(findText)){Dispatch picture = Dispatch.call(Dispatch.get(getSelection(), "InLineShapes").toDispatch(), "AddPicture", imagePath).toDispatch(); Dispatch.call(picture, "Select");Dispatch.put(picture, "Width", new Variant(width));Dispatch.put(picture, "Height", new Variant(height));moveStart();}}/*** 在当前插⼊点中插⼊图⽚* @param imagePath*/public void insertImage(String imagePath, int width, int height){Dispatch picture = Dispatch.call(Dispatch.get(getSelection(), "InLineShapes").toDispatch(), "AddPicture", imagePath).toDispatch(); Dispatch.call(picture, "Select");Dispatch.put(picture, "Width", new Variant(width));Dispatch.put(picture, "Height", new Variant(height));moveRight();}/*** 在当前插⼊点中插⼊图⽚* @param imagePath*/public void insertImage(String imagePath){Dispatch.call(Dispatch.get(getSelection(), "InLineShapes").toDispatch(), "AddPicture", imagePath);}/*** 获取书签的位置* @param bookmarkName* @return书签的位置*/public Dispatch getBookmark(String bookmarkName){try{Dispatch bookmark = Dispatch.call(this.doc, "Bookmarks", bookmarkName).toDispatch();return Dispatch.get(bookmark, "Range").toDispatch();}catch(Exception e){e.printStackTrace();}return null;}/*** 在指定的书签位置插⼊图⽚* @param bookmarkName* @param imagePath*/public void insertImageAtBookmark(String bookmarkName, String imagePath){Dispatch dispatch = getBookmark(bookmarkName);if(dispatch != null)Dispatch.call(Dispatch.get(dispatch, "InLineShapes").toDispatch(), "AddPicture", imagePath);}/*** 在指定的书签位置插⼊图⽚* @param bookmarkName* @param imagePath* @param width* @param height*/public void insertImageAtBookmark(String bookmarkName, String imagePath, int width, int height){Dispatch dispatch = getBookmark(bookmarkName);if(dispatch != null){Dispatch picture = Dispatch.call(Dispatch.get(dispatch, "InLineShapes").toDispatch(), "AddPicture", imagePath).toDispatch();Dispatch.call(picture, "Select");Dispatch.put(picture, "Width", new Variant(width));Dispatch.put(picture, "Height", new Variant(height));}}/*** 在指定的书签位置插⼊⽂本* @param bookmarkName* @param text*/public void insertAtBookmark(String bookmarkName, String text){Dispatch dispatch = getBookmark(bookmarkName);if(dispatch != null)Dispatch.put(dispatch, "Text", text);}/*** ⽂档另存为* @param savePath*/public void saveAs(String savePath){Dispatch.call(doc, "SaveAs", savePath);}/*** ⽂档另存为PDF* <b><p>注意:此操作要求word是2007版本或以上版本且装有加载项:Microsoft Save as PDF 或 XPS</p></b>* @param savePath*/public void saveAsPdf(String savePath){Dispatch.call(doc, "SaveAs", new Variant(17));}/*** 保存⽂档* @param savePath*/public void save(String savePath){Dispatch.call(Dispatch.call(word, "WordBasic").getDispatch(),"FileSaveAs", savePath);}/*** 关闭word⽂档*/public void closeDocument(){if (doc != null) {Dispatch.call(doc, "Close", new Variant(saveOnExit));doc = null;}}public void exit(){word.invoke("Quit", new Variant[0]);}}具体WordUtils类的使⽤暂时没有看到更多的例⼦,上⾯的util的使⽤是⾃⼰摸索出来的,可能不是最优,最恰当的.//==================================================================================================使⽤Java⼯具POI操作MicroSoft Office套件Word,Excle和PPT使⽤Maven⼯程的话需要在Pom.xml⽂件中引⼊的jar包.⼀开始是想使⽤POI⼯具操作,但是从⽹上找来的代码始终报编译错误,代码中的⼀些类找不到,但是也明明已经引⼊了poi-3.x.jar包⽂件,更换了好⼏个poi版本的jar包仍是⼀样的效果.随后调查,到底需要哪些jar包.....结果如下:<dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>3.8</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>3.8</version></dependency><dependency><groupId>org.apache.xmlbeans</groupId><artifactId>xmlbeans</artifactId><version>2.3.0</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-scratchpad</artifactId><version>3.8</version></dependency>所依赖的全部jar包的截图如果只引⼊⼀个poi-3.x.jar包是会报错的. POI具体操作Word,Excel,和PPT的代码,⾃⾏百度.只要jar包引⼊的正确,运⾏编译代码就没有问题.。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
}
wwb.}catch (Exception e) {
e.printStackTrace();
//如果是ExcelException,则直接抛出
if(e instanceof ExcelException){
throw (ExcelException)e;
//否则将其它异常包装成ExcelException再抛出
super(message);
// TODO Auto-generated constructor stub
}
public ExcelException(Throwable cause) {
super(cause);
// TODO Auto-generated constructor stub
}
public ExcelException(String message, Throwable cause) {
super(message, cause);
// TODO Auto-generated constructor stub
}
}
2.POI核心处理
/**
* author : SUNZK-QQ:1131341075
* Date : 2018-8-23下午9:13:21
* Comments :导入导出Excel工具类
//如果只有一个工作表的情况
if(1==sheetNum){
WritableSheet sheet=wwb.createSheet(sheetName, i);
fillSheet(sheet, list, fieldMap, 0, list.size()-1);
//有多个工作表的情况
}else{
WritableSheet sheet=wwb.createSheet(sheetName+(i+1), i);
String sheetName,
int sheetSize,
OutputStream out
) throws ExcelException{
if(list.size()==0 || list==null){
throw new ExcelException("数据源中没有任何数据");
}
if(sheetSize>65535 || sheetSize<1){
sheetSize=65535;
}
//创建工作簿并发送到OutputStream指定的地方
WritableWorkbook wwb;
try {
wwb = Workbook.createWorkbook(out);
//因为2003的Excel一个工作表最多可以有65536条记录,除去列头剩下65535条
* Version : 1.0.0
*/
public class ExcelUtil {
/**
* MethodName : listToExcel
* Description :导出Excel(可以导出到本地文件系统,也可以导出到浏览器,可自定义工作表大小)
* param list数据源
* param fieldMap类的英文属性和Excel中的中文列名的对应关系
* param fieldMap类的英文属性和Excel中的中文列名的对应关系
* param out导出流
* throws ExcelException
*/
public static <T> void listToExcel (
List<T> list ,
LinkedHashMap<String,String> fieldMap,
}else{
throw new ExcelException("导出Excel失败");
}
}
}
/**
* MethodName : listToExcel
* Description :导出Excel(可以导出到本地文件系统,也可以导出到浏览器,工作表大小为2003支持的最大值)
* param list数据源
//获取开始索引和结束索引
int firstIndex=i*sheetSize;
int lastIndex=(i+1)*sheetSize-1>list.size()-1 ? list.size()-1 : (i+1)*sheetSize-1;
//填充工作表
fillSheet(sheet, list, fieldMap, firstIndex, lastIndex);
//所以如果记录太多,需要放到多个工作表中,其实就是个分页的过程
//1.计算一共有多少个工作表
double sheetNum=Math.ceil(list.size()/new Integer(sheetSize).doubleValue());
//2.创建相应的工作表,并向其中填充数据
for(int i=0; i<sheetNum; i++){
* param sheetSize每个工作表中记录的最大个数
* param out导出流
* throws ExcelException
*/
public static <T> void listToExcel (
List<T> list ,
LinkedHashMap<String,String> fieldMap,
JAVA POI
1.Exception处理
public class ExcelException extends Exception {
public ExcelException() {
// TODO Auto-generated constructor stub
}
public ExcelException(String message) {
String sheetName,
OutputStream out
) throws ExcelException{
listToExcel(list, fieldMap, sheetName, 65535, out);
*如果需要的是引用对象的属性,则英文属性使用类似于EL表达式的格式
*如:list中存放的都是student,student中又有college属性,而我们需要学院名称,则可以这样写
* fieldMap.put("college.collegeName","学院名称")
* param sheetName工作表的名称