public static void exportMain(String templatePath){
//获取模板
File file = new File(templatePath);
InputStream is = null;
XSSFWorkbook wb = null;
XSSFSheet sheet = null;
InputStream exportInput = null;
try {
is = new FileInputStream(file);// 将excel文件转为输入流
wb = new XSSFWorkbook(is);// 创建个workbook,
// 获取第一个sheet
sheet = wb.getSheetAt(0);
//存储表头合并部分
Map<String,String> newBtMap = new HashMap<>();
//获取合并部分
for (int i=0;i<sheet.getNumMergedRegions();i++){
CellRangeAddress region = sheet.getMergedRegion(i);
int firstRow = region.getFirstRow();
int firstColumn = region.getFirstColumn();
int lastColumn = region.getLastColumn();
int lastRow = region.getLastRow();
//锁定表头且是列合并的,只是列合并的不管
if (firstRow <3 || firstRow>5 || (lastColumn-firstColumn==0 && lastRow-firstRow>0)){
continue;
}
Row row = sheet.getRow(firstRow);
Cell cell = row.getCell(firstColumn);
String newBtName = cell.toString().trim();
System.out.println("开始列:"+ firstColumn +",结束列:"+ lastColumn +",开始行:"+firstRow+",结束列:"+ lastRow+",值:"+newBtName);
if (StringUtils.isEmpty(newBtName)){
continue;
}
for (int j=firstColumn;j<=lastColumn;j++){
String oldBtName = newBtMap.get(String.valueOf(j));
String newScBtName = "";
if (!StringUtils.isEmpty(oldBtName)){
newScBtName = oldBtName.trim() + "-";
}
newScBtName += newBtName ;
newBtMap.put(String.valueOf(j),newScBtName.replaceAll("\\s*|\r|\n|\t",""));
}
}
System.out.println("合并表头:"+ JSONObject.toJSONString(newBtMap));
// //例子是第四行开始表头
// XSSFRow row3 = sheet.getRow(3);
//
// //获取总列数
// int cellNum = row3.getLastCellNum();
//
// //获取第四行的列
// for (int i=0;i<cellNum;i++){
// XSSFCell cell = row3.getCell(i);
// System.out.println("第4行第"+(i+1)+"列:"+cell.toString());
// }
}catch (Exception e){
e.printStackTrace();
}
}
POI通过模板导出excel(包含表头合并处理)
原创
©著作权归作者所有:来自51CTO博客作者mb650949ff24157的原创作品,请联系作者获取转载授权,否则将追究法律责任
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章
-
poi-tl导出复杂word(图片、表格(合并单元格、嵌套图片)、文字)
java导出复杂word
List java 图片处理 -
java poi实现Excel多级表头导出
java poi实现Excel多级表头导出
测试类 自适应 i++