因為最近工作需要,需要生成一個資料報表,但是資料中有一樣的内容需要合并,是以複雜的地方也就在這,需要不斷周遊目前值判斷和上一個值是否相等來做出相應操作。特别感謝大神“中單大魔王”的程式(
原文連結:https://blog.csdn.net/qq_33142257/article/details/64929145?utm_source=copy)
我在大神的基礎上測試了幾組資料,發現了一些問題,做了相應改動,具體代碼如下。請大家多多指教
public class PoiModel {
private String content;//目前值
private String oldContent;//同一列上一行的值
private int rowIndex;//目前行
private int cellIndex;//目前列
public String getOldContent() {
return oldContent;
}
public void setOldContent(String oldContent) {
this.oldContent = oldContent;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public int getRowIndex() {
return rowIndex;
}
public void setRowIndex(int rowIndex) {
this.rowIndex = rowIndex;
}
public int getCellIndex() {
return cellIndex;
}
public void setCellIndex(int cellIndex) {
this.cellIndex = cellIndex;
}
}
在這裡插入代碼片
import poi.PoiModel;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;
import com.beust.jcommander.internal.Maps;
import com.google.common.collect.Lists;
public class Test{
/**
* @param title 标題集合 tilte的長度應該與list中的model的屬性個數一緻
* @param maps 内容集合
* @param mergeIndex 合并單元格的列
*/
public static String createExcel(String[] title, Map<String/*sheet名*/, List<Map<String/*對應title的值*/, String>>> maps, int[] mergeIndex){
if (title.length==0){
return null;
}
/*初始化excel模闆*/
//Workbook workbook = new XSSFWorkbook();
HSSFWorkbook workbook = new HSSFWorkbook();
Sheet sheet = null;
int n = 0;
/*循環sheet頁*/
for(Map.Entry<String, List<Map<String/*對應title的值*/, String>>> entry : maps.entrySet()){
/*執行個體化sheet對象并且設定sheet名稱,book對象*/
try {
sheet = workbook.createSheet();
workbook.setSheetName(n, entry.getKey());
workbook.setSelectedTab(0);
}catch (Exception e){
e.printStackTrace();
}
/*初始化head,填值标題行(第一行)*/
Row row0 = sheet.createRow(0);
for(int i = 0; i<title.length; i++){
/*建立單元格,指定類型*/
Cell cell_1=row0.createCell(i, CellType.STRING);
//Cell cell_1 = row0.createCell(i,CellType.STRING);
cell_1.setCellValue(title[i]);
}
/*得到目前sheet下的資料集合*/
List<Map<String/*對應title的值*/, String>> list = entry.getValue();
/*周遊該資料集合*/
List<PoiModel> poiModels = Lists.newArrayList();
if(null!=workbook){
Iterator iterator = list.iterator();
int index = 1;/*這裡1是從excel的第二行開始,第一行已經塞入标題了*/
while (iterator.hasNext()){
Row row = sheet.createRow(index);
/*取得目前這行的map,該map中以key,value的形式存着這一行值*/
Map<String, String> map = (Map<String, String>)iterator.next();
/*循環列數,給目前行塞值*/
for(int i = 0; i<title.length; i++){
String old = "";
/*old存的是上一行統一位置的單元的值,第一行是最上一行了,是以從第二行開始記*/
if(index > 1){
old = poiModels.get(i)==null?"":poiModels.get(i).getContent();
}
/*循環需要合并的列*/
for(int j = 0; j < mergeIndex.length; j++){
if(index == 1){
/*記錄第一行的開始行和開始列*/
PoiModel poiModel = new PoiModel();
poiModel.setOldContent(map.get(title[i]));
poiModel.setContent(map.get(title[i]));
poiModel.setRowIndex(1);
poiModel.setCellIndex(i);
poiModels.add(poiModel);
break;
}else if(i > 0 && mergeIndex[j] == i && index<list.size()){/*這邊i>0也是因為第一列已經是最前一列了,隻能從第二列開始*/
/*目前同一列的内容與上一行同一列不同時,把那以上的合并, 或者在目前元素一樣的情況下,前一列的元素并不一樣,這種情況也把以上的合并*/
/*如果不需要考慮“目前行與上一行内容相同,但是它們的前一列内容不一樣則不合并”的情況,把下面條件中||poiModels.get(i).getContent().equals(map.get(title[i])) && !poiModels.get(i - 1).getOldContent().equals(map.get(title[i-1]))去掉就行*/
/*如果後續列合并根據第一列或者指定的列,則将!poiModels.get(i - 1).getOldContent().equals(map.get(title[i-1])中的 i-1 換成0或指定的列*/
if(!poiModels.get(i).getContent().equals(map.get(title[i])) || poiModels.get(i).getContent().equals(map.get(title[i])) && !poiModels.get(i - 1).getOldContent().equals(map.get(title[i-1]))){
if(poiModels.get(i).getRowIndex()!=(index-1)) {
CellRangeAddress cra=new CellRangeAddress(poiModels.get(i).getRowIndex()/*從第二行開始*/, index - 1/*到第幾行*/, poiModels.get(i).getCellIndex()/*從某一列開始*/, poiModels.get(i).getCellIndex()/*到第幾列*/);
//在sheet裡增加合并單元格
/*目前行的目前列與上一行的目前列的内容不一緻時,則把目前行以上的合并*/
sheet.addMergedRegion(cra);
}
/*重新記錄該列的内容為目前内容,行标記改為目前行标記,列标記則為目前列*/
poiModels.get(i).setContent(map.get(title[i]));
poiModels.get(i).setRowIndex(index);
poiModels.get(i).setCellIndex(i);
}
}
/*處理第一列的情況,不包括最後一行*/
if(mergeIndex[j] == i && i == 0 && !poiModels.get(i).getContent().equals(map.get(title[i]))&&index<list.size()){
/*目前行的目前列與上一行的目前列的内容不一緻時,則把目前行以上的合并*/
if(poiModels.get(i).getRowIndex()!=(index-1)) {
CellRangeAddress cra=new CellRangeAddress(poiModels.get(i).getRowIndex()/*從第二行開始*/, index - 1/*到第幾行*/, poiModels.get(i).getCellIndex()/*從某一列開始*/, poiModels.get(i).getCellIndex()/*到第幾列*/);
//在sheet裡增加合并單元格
sheet.addMergedRegion(cra);
}
/*重新記錄該列的内容為目前内容,行标記改為目前行标記*/
poiModels.get(i).setContent(map.get(title[i]));
poiModels.get(i).setRowIndex(index);
poiModels.get(i).setCellIndex(i);
}
/*最後一行的處理,從第一列開始。最後一行沒有後續的行與之比較,是以當到最後一行時則直接合并對應列的相同内容*/
if(mergeIndex[j] == i && index == list.size()){
if(!poiModels.get(i).getContent().equals(map.get(title[i]))&&poiModels.get(i).getRowIndex()!=(index-1)) {
/*目前行的目前列與上一行的目前列的内容不一緻時,則把目前行以上的合并*/
CellRangeAddress cra=new CellRangeAddress(poiModels.get(i).getRowIndex()/*從某行開始*/, index-1/*到第幾行*/, poiModels.get(i).getCellIndex()/*從某一列開始*/, poiModels.get(i).getCellIndex()/*到第幾列*/);
//在sheet裡增加合并單元格
sheet.addMergedRegion(cra);
}
if(poiModels.get(i).getContent().equals(map.get(title[i]))&&!(poiModels.get(i).getRowIndex()>(index-1))) {
if(i==0) {//第一列
CellRangeAddress cra=new CellRangeAddress(poiModels.get(i).getRowIndex()/*從第某行開始*/, index/*到第幾行*/, poiModels.get(i).getCellIndex()/*從某一列開始*/, poiModels.get(i).getCellIndex()/*到第幾列*/);
//在sheet裡增加合并單元格
sheet.addMergedRegion(cra);
}
else {//其他列
if(poiModels.get(i - 1).getOldContent().equals(map.get(title[i-1]))) {
CellRangeAddress cra=new CellRangeAddress(poiModels.get(i).getRowIndex()/*從某行開始*/, index/*到第幾行*/, poiModels.get(i).getCellIndex()/*從某一列開始*/, poiModels.get(i).getCellIndex()/*到第幾列*/);
//在sheet裡增加合并單元格
sheet.addMergedRegion(cra);
}
}
}
poiModels.get(i).setContent(map.get(title[i]));
poiModels.get(i).setRowIndex(index);
poiModels.get(i).setCellIndex(i);
}
}// for(int j = 0; j < mergeIndex.length; j++)
Cell cell=row0.createCell(i, CellType.STRING);
cell.setCellValue(map.get(title[i]));
/*在每一個單元格處理完成後,把這個單元格内容設定為old内容*/
poiModels.get(i).setOldContent(old);
}
index++;
}
}
n++;
}
/*生成臨時檔案*/
FileOutputStream out = null;
String localPath = null;
File tempFile = null;
String fileName = "D:\\excel\\"+String.valueOf(new Date().getTime()/1000);
try {
tempFile = File.createTempFile(fileName, ".xlsx");
localPath = tempFile.getAbsolutePath();
out = new FileOutputStream(localPath);
workbook.write(out);
}catch (IOException e){
e.printStackTrace();
}finally {
try {
out.flush();
out.close();
}catch (IOException e){
e.printStackTrace();
}
}
return localPath;
}
public static void main(String[] args) throws IOException{
/*此處标題的數組則對應excel的标題*/
String[] title = {"id","标題","描述","負責人","開始時間"};
List<Map<String, String>> list = Lists.newArrayList();
/*這邊是制造一些資料,注意每個list中map的key要和标題數組中的元素一緻*/
for(int i = 0; i<10; i++){
HashMap<String, String> map = com.google.common.collect.Maps.newHashMap();
if(i > 5){
if(i<7){
map.put("id","333");
map.put("标題","mmmm");
}else {
map.put("id","333");
map.put("标題","aaaaa");
}
}else if (i >3){
map.put("id","222");
map.put("标題","哈哈哈哈");
}else if (i>1 && i<3){
map.put("id","222");
map.put("标題","hhhhhhhh");
}else {
map.put("id","222");
map.put("标題","bbbb");
}
map.put("描述","sssssss");
map.put("負責人","vvvvv");
map.put("開始時間","2017-02-27 11:20:26");
list.add(map);
}
Map<String/*此處的key為每個sheet的名稱,一個excel中可能有多個sheet頁*/, List<Map<String/*此處key對應每一列的标題*/, String>>/*該list為每個sheet頁的資料*/> map = Maps.newHashMap();
map.put("測試合并資料", list);
System.out.println(createExcel(title, map, new int[]{0,1,2}/*此處數組為需要合并的列,可能有的需求是隻需要某些列裡面相同内容合并*/));
}
}
這是第一組數值
這是我第二組測試資料,看第三列因為是根據前一列(第二列)合并的
這是第三組,我把從第二列及後續合并準則設為以第一列為準,這和第二張圖比較一下就很明顯啦
這幾天天天在琢磨,真的是頭都大了,哈哈哈,再次感謝樓主 中單大魔王 !