已完成

  • sheet页隐藏
  • 冻结的单元格
  • 设置默认行高
  • 合并单元格
  • 下拉列表(单元格校验)
  • 设置行高
  • 设置列样式
  • 设置列宽
  • 设置单元格样式
  • 设置单元格字体
  • 设置单元格批注

项目地址

package xxx.common.utils;
import xxx.common.entity.ExcelCell;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.apache.poi.ss.util.PaneInformation;
import org.apache.poi.xssf.usermodel.*;
import java.util.*;import static org.apache.poi.ss.usermodel.CellType.*;public class ExcelUtil {/*** 获取合并单元格的值* @param sheet* @param row* @param column* @return*/public static ExcelCell getMergedRegionEntity(Sheet sheet , int row , int column){int sheetMergeCount = sheet.getNumMergedRegions();for(int i = 0 ; i < sheetMergeCount ; i++){CellRangeAddress ca = sheet.getMergedRegion(i);int firstColumn = ca.getFirstColumn();int lastColumn = ca.getLastColumn();int firstRow = ca.getFirstRow();int lastRow = ca.getLastRow();if(row >= firstRow && row <= lastRow){if(column >= firstColumn && column <= lastColumn){Row fRow = sheet.getRow(firstRow);Cell fCell = fRow.getCell(firstColumn);ExcelCell cell = new ExcelCell();cell.setMergedRegion(true);cell.setFirstColumn(firstColumn);cell.setLastColumn(lastColumn);cell.setFirstRow(firstRow);cell.setLastRow(lastRow);cell.setValue(getCellValue(fCell));return cell;}}}return null ;}/*** 判断指定的单元格是否是合并单元格* @param sheet* @param row* @param column* @return*/public static boolean isMergedRegion(Sheet sheet , int row , int column){int sheetMergeCount = sheet.getNumMergedRegions();for(int i = 0 ; i < sheetMergeCount ; i++ ){CellRangeAddress ca = sheet.getMergedRegion(i);int firstColumn = ca.getFirstColumn();int lastColumn = ca.getLastColumn();int firstRow = ca.getFirstRow();int lastRow = ca.getLastRow();if(row >= firstRow && row <= lastRow){if(column >= firstColumn && column <= lastColumn){return true ;}}}return false ;}/*** 获取单元格的值* @param cell* @return*/public static String getCellValue(Cell cell){if(cell == null) return "";if(cell.getCellType() == STRING){return cell.getStringCellValue();}else if(cell.getCellType() == BOOLEAN){return String.valueOf(cell.getBooleanCellValue());}else if(cell.getCellType() == FORMULA){return cell.getCellFormula() ;}else if(cell.getCellType() == NUMERIC){return String.valueOf(cell.getNumericCellValue());}return "";}/*** 转换 AA => 27* @param rowName* @return* @throws Exception*/public static Integer getCellRowIndex(String rowName) throws Exception {Integer A_charAt = Integer.valueOf('A');Integer Z_charAt = Integer.valueOf('Z');Integer full = Z_charAt - A_charAt;char[] codeList = rowName.toUpperCase().toCharArray();Integer offset = A_charAt - 1;int num = 0;for (int i=0; i<codeList.length; i++) {char chr = codeList[i];Integer chr_charAt = Integer.valueOf(chr);if (chr_charAt < A_charAt|| chr_charAt > Z_charAt) {throw new Exception("非法的单元格位置!");}num += (chr_charAt - offset) + full * i;}return num;}/*** 分割cell地址* AAA111 => { x: AAA, y:111 }* @param cellAddr* @return*/public static Map<String, String> splitSingleCellAddr(String cellAddr) {String x = new String(cellAddr);String y = new String(cellAddr);x = x.replaceAll("\\d+", "");y = y.replaceAll("[a-zA-Z]+", "");Map<String, String> res = new HashMap<>();res.put("x", x);res.put("y", y);return res;}/*** 将xls转换为xlsx* @param xls* @return*/public static XSSFWorkbook xls2xlsx(HSSFWorkbook xls) {int sheetNum = xls.getNumberOfSheets();XSSFWorkbook newXlsx = new XSSFWorkbook();for (int i=0; i<sheetNum; i++) {HSSFSheet oldSheet = xls.getSheetAt(i);XSSFSheet newSheet = newXlsx.createSheet(oldSheet.getSheetName());oldSheet.getActiveCell();// sheet页隐藏if (xls.isSheetHidden(i)) {newXlsx.setSheetHidden(i, true);}// 冻结的单元格 okPaneInformation paneInformation = oldSheet.getPaneInformation();if (!Objects.isNull(paneInformation)) {newSheet.createFreezePane(paneInformation.getVerticalSplitPosition(), paneInformation.getHorizontalSplitPosition(),paneInformation.getVerticalSplitLeftColumn(), paneInformation.getHorizontalSplitTopRow());}// 这个不知道是设置什么 ?int[] oldColumnBreaks = oldSheet.getColumnBreaks();for (int j : oldColumnBreaks) {newSheet.setColumnBreak(j);}// 设置默认行高newSheet.setDefaultRowHeightInPoints(oldSheet.getDefaultRowHeightInPoints());newSheet.setDefaultRowHeight(oldSheet.getDefaultRowHeight());newSheet.setDefaultColumnWidth(oldSheet.getDefaultColumnWidth());// 合并单元格 OKList<CellRangeAddress> mergeRegins = oldSheet.getMergedRegions();for (int j = 0; j < mergeRegins.size(); j++) {newSheet.addMergedRegion(mergeRegins.get(j));}// 保护单元格 @TODO// 下拉列表(单元格校验) OKXSSFDataValidationHelper helper = new XSSFDataValidationHelper(newSheet);List<HSSFDataValidation> validationList = oldSheet.getDataValidations();for (HSSFDataValidation item : validationList) {CellRangeAddressList cellRangeAddressList = item.getRegions();DataValidationConstraint dvConstraint =  item.getValidationConstraint();XSSFDataValidationConstraint dv = copyDataValidationConstraint(dvConstraint);DataValidation dataValidation = helper.createValidation(dv, cellRangeAddressList);newSheet.addValidationData(dataValidation);}// 单元格的值for (int j = 0; j <= oldSheet.getLastRowNum(); j++) {HSSFRow row = oldSheet.getRow(j);if(row != null){XSSFRow newRow = newSheet.getRow(j);if (Objects.isNull(newRow)) newRow = newSheet.createRow(j);// 设置行高 OKnewRow.setHeight(row.getHeight());newRow.setHeightInPoints(row.getHeightInPoints());// 隐藏列 —— 无效newRow.setZeroHeight(row.getZeroHeight());// 设置列样式 OKXSSFCellStyle newStyle = newXlsx.createCellStyle();if (!Objects.isNull(row.getRowStyle())) {HSSFFont oldFont = row.getRowStyle().getFont(xls);if (!Objects.isNull(oldFont)) {XSSFFont newFont = newXlsx.createFont();transXSSFFont(oldFont, newFont);newStyle.setFont(newFont);}}transXSSFStyle(row.getRowStyle(), newStyle);newRow.setRowStyle(newStyle);for (int k = oldSheet.getRow(j).getFirstCellNum(); k < oldSheet.getRow(j).getLastCellNum(); k++) {// 设置列宽 OKnewSheet.setColumnWidth(k, oldSheet.getColumnWidth(k));// 获取每个单元格HSSFCell cell = row.getCell(k);if (cell == null) {continue;}XSSFCell newCell = newRow.getCell(k);// 隐藏行 —— 无效if (oldSheet.isColumnHidden(k)) {newSheet.setColumnHidden(k, true);}if (Objects.isNull(newCell)) newCell = newRow.createCell(k);// 设置单元格样式 OKXSSFCellStyle newCellStyle = newXlsx.createCellStyle();transXSSFStyle(cell.getCellStyle(), newCellStyle);// 设置单元格字体if (!Objects.isNull(cell.getCellStyle())) {HSSFFont oldFont = cell.getCellStyle().getFont(xls);if (!Objects.isNull(oldFont)) {XSSFFont newFont = newXlsx.createFont();transXSSFFont(oldFont, newFont);newCellStyle.setFont(newFont);}}newCell.setCellStyle(newCellStyle);// 设置单元格批注 OK// 批注值 yesXSSFComment newComment = copyComment(cell, newSheet.createDrawingPatriarch());// 批注样式 no// 将批注添加到单元格对象中newCell.setCellComment(newComment);// 设置单元格公式 OKnewCell.setHyperlink(cell.getHyperlink());// 设置单元格值 OKnewCell.setCellType(cell.getCellType());switch (cell.getCellType()) {case STRING:newCell.setCellValue(cell.getRichStringCellValue().getString());break;case NUMERIC:if (org.apache.poi.ss.usermodel.DateUtil.isCellDateFormatted(cell)) {newCell.setCellValue(cell.getDateCellValue());} else {newCell.setCellValue(cell.getNumericCellValue());}break;case BOOLEAN:newCell.setCellValue(cell.getBooleanCellValue());break;case FORMULA:newCell.setCellFormula(cell.getCellFormula());break;case ERROR:newCell.setCellErrorValue(cell.getErrorCellValue());default:newCell.setCellValue("");break;}}}}}return newXlsx;}/*** 迁移字体* @param oldFont* @param newFont*/private static void transXSSFFont(HSSFFont oldFont, XSSFFont newFont) {newFont.setBold(oldFont.getBold());newFont.setFontName(oldFont.getFontName());newFont.setColor(oldFont.getColor());newFont.setFontHeightInPoints(oldFont.getFontHeightInPoints());newFont.setItalic(oldFont.getItalic());newFont.setCharSet(oldFont.getCharSet());newFont.setFontHeight(oldFont.getFontHeight());newFont.setStrikeout(oldFont.getStrikeout());newFont.setTypeOffset(oldFont.getTypeOffset());newFont.setUnderline(oldFont.getUnderline());}/*** 复制注解* @param cell* @param newDrawing* @return*/private static XSSFComment copyComment(HSSFCell cell, XSSFDrawing newDrawing) {HSSFComment oldComment = cell.getCellComment();if (Objects.isNull(oldComment)) return null;ClientAnchor anchor = new XSSFClientAnchor();// 关键修改anchor.setDx1(0);anchor.setDx2(0);anchor.setDy1(0);anchor.setDy2(0);anchor.setCol1(cell.getColumnIndex());anchor.setRow1(cell.getRowIndex());anchor.setCol2(cell.getColumnIndex() + 5);anchor.setRow2(cell.getRowIndex() + 6);// 结束XSSFComment comment = newDrawing.createCellComment(anchor);// 输入批注信息HSSFRichTextString str = oldComment.getString();XSSFRichTextString newStr = copyRichTextString(str);comment.setString(newStr);return comment;}/*** 复制富文本* @param str* @return*/private static XSSFRichTextString copyRichTextString(HSSFRichTextString str) {XSSFRichTextString newStr = new XSSFRichTextString();newStr.setString(str.getString());return newStr;}/*** 复制下拉框* @param dvConstraint* @return*/private static XSSFDataValidationConstraint copyDataValidationConstraint(DataValidationConstraint dvConstraint) {System.out.println(dvConstraint.getExplicitListValues());XSSFDataValidationConstraint dv = new XSSFDataValidationConstraint(dvConstraint.getExplicitListValues());dv.setOperator(dvConstraint.getOperator());if (!Objects.isNull(dvConstraint.getFormula1())) {dv.setFormula1(dvConstraint.getFormula1());}if (!Objects.isNull(dvConstraint.getFormula2())) {dv.setFormula2(dvConstraint.getFormula2());}return dv;}/*** 转换单元格属性* @param oldStyle* @param newStyle*/public static void transXSSFStyle(HSSFCellStyle oldStyle, XSSFCellStyle newStyle) {if (Objects.isNull(oldStyle)) return ;newStyle.setAlignment(oldStyle.getAlignment());newStyle.setVerticalAlignment(oldStyle.getVerticalAlignment());newStyle.setBorderBottom(oldStyle.getBorderBottom());newStyle.setBorderLeft(oldStyle.getBorderLeft());newStyle.setBorderRight(oldStyle.getBorderRight());newStyle.setBorderTop(oldStyle.getBorderTop());newStyle.setBottomBorderColor(oldStyle.getBottomBorderColor());newStyle.setTopBorderColor(oldStyle.getTopBorderColor());newStyle.setLeftBorderColor(oldStyle.getLeftBorderColor());newStyle.setRightBorderColor(oldStyle.getRightBorderColor());newStyle.setFillForegroundColor(oldStyle.getFillForegroundColor());newStyle.setFillPattern(oldStyle.getFillPattern());
//        newStyle.setFont(oldStyle.getFont());newStyle.setWrapText(oldStyle.getWrapText());newStyle.setDataFormat(oldStyle.getDataFormat());newStyle.setFillBackgroundColor(oldStyle.getFillForegroundColor());newStyle.setHidden(oldStyle.getHidden());newStyle.setIndention(oldStyle.getIndention());newStyle.setLocked(oldStyle.getLocked());newStyle.setQuotePrefixed(oldStyle.getQuotePrefixed());newStyle.setRotation(oldStyle.getRotation());newStyle.setShrinkToFit(oldStyle.getShrinkToFit());}}

Java简单实现xls转xlsx相关推荐

  1. java excel api xlsx_Java 解析Excel(xls、xlsx两种格式)

    Java 解析Excel(xls.xlsx两种格式) 一.环境 JDK 1.8 二.JAR 1.commons-collections4-4.1.jar 2.poi-3.9-20121203.jar ...

  2. java 解析xls 文件_java简单解析xls文件的方法示例【读取和写入】

    本文实例讲述了java简单解析xls文件的方法.分享给大家供大家参考,具体如下: 读取: import java.io.*; import jxl.*; import jxl.write.*; imp ...

  3. android excel 筛选功能,Android 实现 Excel 解析 xls 和 xlsx,方法也可以很简单

    Excel 解析,一般来说是在服务端进行的,但是如果移动端要实现解析Excel的功能,那也是有实现的方法的. 不过由于Android 原生用Java/Kotlin实现,所以也可以参考服务端解析Exce ...

  4. Java解析Excel工具类(兼容xls和xlsx)

    依赖jar <dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml< ...

  5. java 兼容excel_Java解析Excel工具类(兼容xls和xlsx)

    依赖jar org.apache.poi poi-ooxml 4.0.1 ExcelUtils.java package javax.utils; import java.io.File; impor ...

  6. java xlsx怎么转换成excel格式_python小工具 | Excel的xls和xlsx格式文件转换

    众所周知Excel文件格式转换可以通过"另存为"的方式转换格式,可以说是简单方便,但是对于大量文件转换或者经常重复进行转换操作时,这种方法就很不方便. 显然利用程序对xls和xls ...

  7. Java 解析Excel(xls、xlsx两种格式)

    Java 解析Excel(xls.xlsx两种格式) 一.环境 JDK 1.8 二.JAR 1.commons-collections4-4.1.jar 2.poi-3.9-20121203.jar ...

  8. java使用poi读取存储excel表格,包括xls和xlsx格式

    全栈工程师开发手册 (作者:栾鹏) java教程全解 java使用poi读取存储excel表格,包括xls和xlsx格式. 需要导入的包 poi-3.14.jar poi-ooxml-3.14.jar ...

  9. Java实现XLS和XLSX之间的相互转换

    文章目录 前言 一.程序环境 二.格式转换 1.将XLS转换为XLSX 代码示例 效果图 2.将XLSX转换为XLS 代码示例 效果图 前言 当你在较新版本的Microsoft Excel中打开一个X ...

最新文章

  1. SQLServer数据库获取重复记录中日期最新的记录
  2. UI素材|标签页 Tab实用案例,可临摹学习
  3. 非模态对话框的销毁及消息的发送顺序
  4. 深入分析同步工具类之AbstractQueuedSynchronizer
  5. chap6_2 Parallax mapping in OGRE
  6. MyReport:DataGrid的打印和打印预览
  7. 【数据库原理实验(openGauss)】 安全性控制
  8. 曲演杂坛--SQLCMD下执行命令失败但没有任何错误提示的坑
  9. React-Native 双平台应用的测试发布和 CodePush 热更新部署
  10. PDF文件不能正常显示问题的原因及解决方法(图文)
  11. 万用表怎么测电池内阻_万用表怎么测量电阻
  12. 批量Word转换成PDF,用这方法超简单
  13. 详细讲解修改allure报告自定义的logo和名称中文
  14. git 码云 简要使用
  15. Java第十天笔记01——文件与流
  16. Xquartz远程访问linux
  17. [珍藏] 技能图谱握在手,召唤神龙不用愁
  18. 木块问题(Uva101)
  19. 基于单片机的A/D数字电压表设计(电路+程序)
  20. 终于有人把云计算、大数据和 AI 讲明白了

热门文章

  1. springBoot上传文件大小受限制的解决方案
  2. flash骨骼动画资料
  3. JS字符串替换所有的某个字符
  4. Buuctf 神奇的二维码
  5. L1-2 太神奇了 (5 分)
  6. 加密文件python
  7. AI智能安防平台EasyCVR视频融合云服务平台云端录像展示优化
  8. RDkit&mol2vec :基于逻辑回归的靶标抑制剂活性二分类对比
  9. 《御龙传奇》6.23正式上线链游玩家 | 万众期待、创世归来
  10. 记录解决 <应用程序无法正常启动(0xc0000142) > 的过程