wisdomisite-java/src/main/java/com/zhgd/xmgl/util/JxlExcelUtils.java
2024-04-14 21:05:01 +08:00

628 lines
27 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* @Author:gongyijun
* @Title: JxlExcelUtils.java
* @Package com.siwa.shop.utils
* @Description: TODO
* @author A18ccms A18ccms_gmail_com
* @date 2017年8月8日 下午4:39:06
* @version V1.0
*/
package com.zhgd.xmgl.util;
import com.zhgd.xmgl.base.MergeRecord;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.WorkbookSettings;
import jxl.format.UnderlineStyle;
import jxl.write.*;
import jxl.write.biff.RowsExceededException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang3.ArrayUtils;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
/**
* @author A18ccms a18ccms_gmail_com
* @Author:gongyijun
* @ClassName: JxlExcelUtils
* @Description: TODO
* @date 2017年8月8日 下午4:39:06
*/
@Slf4j
public class JxlExcelUtils {
public static void main(String[] args) throws Exception {
String path = "D:/广东省统表.xls";
List<Map<String, String>> list = jxlExlToList(path);
log.info(list.toString());
}
public static List<Map<String, String>> jxlExlToList(String path) throws Exception {
Workbook book = null;
List<Map<String, String>> list = null;
try {
File os = new File(path);
if (!os.exists()) {
// 如果指定文件不存在,则新建该文件
boolean mkdirs = os.createNewFile();
log.info("{}", mkdirs);
}
book = Workbook.getWorkbook(os);// 创建一个新的写入工作簿
Sheet sheet = book.getSheet(0);
int totalRows = sheet.getRows();
int totalColumns = sheet.getColumns();
Cell[] cell = sheet.getRow(0);
if (totalColumns <= 0) {
return null;
}
//读取第一行作为Map中的key
List<String> tableHeaderlist = new ArrayList<>();
for (int i = 0; i < totalColumns; i++) {
tableHeaderlist.add(cell[i].getContents());
}
//将每一行存为Map集合然后存为list
list = new ArrayList<>();
Map<String, String> rowData = new LinkedHashMap<>();
for (int i = 1; i < totalRows; i++) {
cell = sheet.getRow(i);
rowData = new LinkedHashMap<>(totalColumns);
for (int j = 0; j < cell.length; j++) {
rowData.put(tableHeaderlist.get(j).toString(), cell[j].getContents());
}
list.add(rowData);
}
log.info("工作簿读取数据成功!");
book.close();// 关闭
} catch (Exception e) {
log.error("error", e);
}
return list;
}
public static List<Map<String, String>> jxlExlToList(String path, int index) throws Exception {
Workbook book = null;
List<Map<String, String>> list = null;
try {
File os = new File(path);
if (!os.exists()) {
// 如果指定文件不存在,则新建该文件
boolean mkdirs = os.createNewFile();
log.info("{}", mkdirs);
}
book = Workbook.getWorkbook(os);// 创建一个新的写入工作簿
Sheet sheet = book.getSheet(0);
int totalRows = sheet.getRows();
int totalColumns = sheet.getColumns();
Cell[] cell = sheet.getRow(index);
if (totalColumns <= 0) {
return null;
}
//读取指定行作为Map中的key
List<String> tableHeaderlist = new ArrayList<>();
for (int i = 0; i < totalColumns; i++) {
tableHeaderlist.add(cell[i].getContents());
}
//将指定行后面每一行存为Map集合然后存为list
list = new ArrayList<>();
Map<String, String> rowData = new LinkedHashMap<>();
int start = 1 + index;
for (int i = start; i < totalRows; i++) {
cell = sheet.getRow(i);
rowData = new LinkedHashMap<>(totalColumns);
for (int j = 0; j < cell.length; j++) {
rowData.put(tableHeaderlist.get(j).toString(), cell[j].getContents());
}
list.add(rowData);
}
log.info("工作簿读取数据成功!");
book.close();// 关闭
} catch (Exception e) {
log.error("error", e);
}
return list;
}
public static List<Map<String, String>> jxlExlToList(InputStream is, int index) throws Exception {
Workbook book = null;
List<Map<String, String>> list = null;
try {
/*File os = new File(path);
if (!os.exists()) {
// 如果指定文件不存在,则新建该文件
os.createNewFile();
}*/
book = Workbook.getWorkbook(is);// 创建一个新的写入工作簿
Sheet sheet = book.getSheet(0);
int totalRows = sheet.getRows();
//int totalColumns = sheet.getColumns();
Cell[] cell = sheet.getRow(index);
int totalColumns = cell.length;
if (totalColumns <= 0) {
return null;
}
//读取指定行作为Map中的key
List<String> tableHeaderlist = new ArrayList<>();
for (int i = 0; i < totalColumns; i++) {
tableHeaderlist.add(cell[i].getContents());
}
//将指定行后面每一行存为Map集合然后存为list
list = new ArrayList<>();
Map<String, String> rowData = new LinkedHashMap<>();
int start = 1 + index;
for (int i = start; i < totalRows; i++) {
cell = sheet.getRow(i);
rowData = new LinkedHashMap<>(totalColumns);
for (int j = 0; j < cell.length; j++) {
if (j < totalColumns) {
rowData.put(tableHeaderlist.get(j).toString(), cell[j].getContents());
}
}
list.add(rowData);
}
log.info("工作簿读取数据成功!");
book.close();// 关闭
} catch (Exception e) {
log.error("error", e);
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
log.error("error", e);
}
}
}
return list;
}
/**
* 根据数据列表及参数输出工作薄
*
* @param os 输出流
* @param dataList 数据列表
* @param heads 字段名称
* @param headsStr 字段
* @throws IOException
* @throws WriteException
* @throws RowsExceededException
* @throws NoSuchMethodException
* @throws InvocationTargetException
* @throws IllegalAccessException
* @author 巩浩 2016-7-7 下午2:32:38
*/
@SuppressWarnings("rawtypes")
public static WritableWorkbook createWorkBookWithStyle(OutputStream os, List dataList, String[] heads,
String[] headsStr) throws IOException, RowsExceededException, WriteException, IllegalAccessException,
InvocationTargetException, NoSuchMethodException {
// 根据数据大小具体分n个sheet页默认一页存储10000条数据
int sizeLoop = dataList.size();// 数据大小
int size = dataList.size();
if (sizeLoop < 10000) {
sizeLoop = 10000;
}
int sheetSize = 10000;
int loopSize = sizeLoop / sheetSize;
if (sizeLoop % sheetSize != 0) {
loopSize += 1;
}
// 设置样式
WritableFont wf_head = new WritableFont(WritableFont.ARIAL, 11, WritableFont.BOLD, false,
UnderlineStyle.NO_UNDERLINE, jxl.format.Colour.BLACK); // 定义格式 字体 下划线 斜体 粗体 颜色
WritableFont wf_table = new WritableFont(WritableFont.ARIAL, 10, WritableFont.NO_BOLD, false,
UnderlineStyle.NO_UNDERLINE, jxl.format.Colour.BLACK); // 定义格式 字体 下划线 斜体 粗体 颜色
WritableCellFormat wcf_head = new WritableCellFormat(wf_head); // 单元格定义
wcf_head.setBackground(Colour.GRAY_25);
wcf_head.setAlignment(jxl.format.Alignment.CENTRE); // 设置对齐方式
WritableCellFormat wcf_table = new WritableCellFormat(wf_table);
wcf_table.setAlignment(jxl.format.Alignment.CENTRE);
wcf_table.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);
// 创建一个工作薄
WorkbookSettings workbookSettings = new WorkbookSettings();
workbookSettings.setEncoding("UTF-8"); // 解决中文乱
WritableWorkbook ws = Workbook.createWorkbook(os, workbookSettings);
// 分别往每个sheet页写数据
for (int l = 0; l < loopSize; l++) {
WritableSheet sheet = ws.createSheet("" + (l + 1) + "", l);
for (int i = 0; i < heads.length; i++) {
Label cell = new Label(i, 0, heads[i], wcf_head);
sheet.addCell(cell);
}
// 循环读取数据列表
int n = 1;
for (int i = l * sheetSize; i < (l + 1) * sheetSize && i <= size - 1; i++) {
Object vrd = dataList.get(i);
for (int j = 0; j < headsStr.length; j++) {
Object value = PropertyUtils.getProperty(vrd, headsStr[j]);
if (value != null) {
sheet.setColumnView(j, value.toString().length() + 10);
sheet.addCell(new Label(j, n, value.toString(), wcf_table));
}
}
n++;
}
}
return ws;
}
/**
* jxl导出excel方法
*
* @param fileName 文件名
* @param heads 字段名称(例:{姓名,年龄}
* @param headsStr 字段(例:{nameage}
* @param dataList 数据列表
* @author 巩浩 2016-7-7 下午2:17:47
*/
@SuppressWarnings("rawtypes")
public static void excelExport(String fileName, String[] heads, String[] headsStr, List dataList,
HttpServletResponse response) throws Exception {
WritableWorkbook book = null;
OutputStream os = null;
try {
fileName = new String(fileName.getBytes(), "ISO8859-1") + ".xls";
os = response.getOutputStream();
response.reset();// 清空输出流
response.setHeader("Content-disposition", "attachment; filename=" + fileName);
// 设定输出文件头
response.setContentType("application/msexcel");// 定义输出类型
if (dataList != null && dataList.size() > 0) {
book = createWorkBookWithStyle(os, dataList, heads, headsStr);
} else {
book = Workbook.createWorkbook(os);
WritableSheet sheet = book.createSheet("数据", 0);
// 指定单元格位置(如:第一列第一行(0, 0))以及单元格内容为(如:小明)
for (int i = 0; i < heads.length; i++) {
Label cell = new Label(i, 0, heads[i]);
// 将定义好的单元格添加到工作表中
sheet.addCell(cell);
}
}
book.write();
} catch (Exception e) {
log.error("error", e);
} finally {
if (book != null) {
book.close();
}
if (os != null) {
os.close();
}
}
}
public static void excelManySheetExport(String fileName, List<Map<String, Object>> sheetList, HttpServletResponse response) throws Exception {
WritableWorkbook book = null;
OutputStream os = null;
try {
fileName = new String(fileName.getBytes(), "ISO8859-1") + ".xls";
os = response.getOutputStream();
response.reset();// 清空输出流
response.setHeader("Content-disposition", "attachment; filename=" + fileName);
// 设定输出文件头
response.setContentType("application/msexcel");
book = createManySheetkWithStyle(os, sheetList);
book.write();
} catch (Exception e) {
log.error("error", e);
} finally {
if (book != null) {
book.close();
}
if (os != null) {
os.close();
}
}
}
@SuppressWarnings("rawtypes")
public static WritableWorkbook createManySheetkWithStyle(OutputStream os, List<Map<String, Object>> sheetList) throws IOException, RowsExceededException, WriteException, IllegalAccessException,
InvocationTargetException, NoSuchMethodException {
// 设置样式
WritableFont wf_head = new WritableFont(WritableFont.ARIAL, 11, WritableFont.BOLD, false,
UnderlineStyle.NO_UNDERLINE, jxl.format.Colour.RED); // 定义格式 字体 下划线 斜体 粗体 颜色
WritableFont wf_table = new WritableFont(WritableFont.ARIAL, 10, WritableFont.NO_BOLD, false,
UnderlineStyle.NO_UNDERLINE, jxl.format.Colour.BLACK); // 定义格式 字体 下划线 斜体 粗体 颜色
WritableCellFormat wcf_head = new WritableCellFormat(wf_head); // 单元格定义
wcf_head.setAlignment(jxl.format.Alignment.CENTRE); // 设置对齐方式
WritableCellFormat wcf_table = new WritableCellFormat(wf_table);
wcf_table.setAlignment(jxl.format.Alignment.CENTRE);
wcf_table.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);
// 创建一个工作薄
WorkbookSettings workbookSettings = new WorkbookSettings();
workbookSettings.setEncoding("UTF-8"); // 解决中文乱
WritableWorkbook ws = Workbook.createWorkbook(os, workbookSettings);
// 分别往每个sheet页写数据
for (int l = 0; l < sheetList.size(); l++) {
Map<String, Object> map = sheetList.get(l);
List dataList = (List) map.get("dataList");
String[] heads = (String[]) map.get("heads");
String[] headsStr = (String[]) map.get("headsStr");
int sizeLoop = dataList.size();// 数据大小
int size = dataList.size();
if (sizeLoop < 10000) {
sizeLoop = 10000;
}
int sheetSize = 10000;
int loopSize = sizeLoop / sheetSize;
if (sizeLoop % sheetSize != 0) {
loopSize += 1;
}
if (loopSize > 1) {
// 分别往每个sheet页写数据
for (int dl = 0; dl < loopSize; dl++) {
WritableSheet sheet = ws.createSheet("" + (dl + 1) + "", dl);
for (int i = 0; i < heads.length; i++) {
Label cell = new Label(i, 0, heads[i], wcf_head);
sheet.addCell(cell);
}
// 循环读取数据列表
int n = 1;
for (int i = dl * sheetSize; i < (dl + 1) * sheetSize && i <= size - 1; i++) {
Object vrd = dataList.get(i);
for (int j = 0; j < headsStr.length; j++) {
Object value = PropertyUtils.getProperty(vrd, headsStr[j]);
if (value != null) {
sheet.setColumnView(j, value.toString().length() + 10);
sheet.addCell(new Label(j, n, value.toString(), wcf_table));
}
}
n++;
}
}
} else {
WritableSheet sheet = ws.createSheet(String.valueOf(map.get("sheetName").toString()), l);
for (int i = 0; i < heads.length; i++) {
Label cell = new Label(i, 0, heads[i], wcf_head);
sheet.addCell(cell);
}
// 循环读取数据列表
int n = 1;
for (int i = 0; i <= dataList.size() - 1; i++) {
Object vrd = dataList.get(i);
for (int j = 0; j < headsStr.length; j++) {
Object value = PropertyUtils.getProperty(vrd, headsStr[j]);
if (value != null) {
sheet.setColumnView(j, value.toString().length() + 10);
sheet.addCell(new Label(j, n, value.toString(), wcf_table));
}
}
n++;
}
}
}
return ws;
}
/**
* jxl导出excel方法
*
* @param fileName 文件名
* @param heads 字段名称(例:{姓名,年龄}
* @param headsStr 字段(例:{nameage}
* @param dataList 数据列表
* @param columnStr 合并列内容相同单元格的列 例:{12}
* @author 巩浩 2016-7-7 下午2:17:47
*/
@SuppressWarnings("rawtypes")
public static void excelExportMergeCell(String fileName, String[] heads, String[] headsStr, List dataList, int[] columnStr, String headTitle,
HttpServletResponse response) throws Exception {
WritableWorkbook book = null;
OutputStream os = null;
try {
fileName = new String(fileName.getBytes(), "ISO8859-1") + ".xls";
os = response.getOutputStream();
response.reset();// 清空输出流
response.setHeader("Content-disposition", "attachment; filename=" + fileName);
// 设定输出文件头
response.setContentType("application/msexcel");// 定义输出类型
if (dataList != null && dataList.size() > 0) {
book = createMergeCellWorkBookWithStyle(os, dataList, heads, headsStr, columnStr, headTitle);
} else {
book = Workbook.createWorkbook(os);
WritableSheet sheet = book.createSheet("sheet", 0);
WritableFont wf_headt = new WritableFont(WritableFont.ARIAL, 20, WritableFont.BOLD, false,
UnderlineStyle.NO_UNDERLINE, jxl.format.Colour.BLACK);
WritableCellFormat wcf_head1 = new WritableCellFormat(wf_headt); // 单元格定义
wcf_head1.setAlignment(jxl.format.Alignment.CENTRE); // 设置对齐方式
sheet.mergeCells(0, 0, heads.length - 1, 0);
Label cell0 = new Label(0, 0, headTitle, wcf_head1);
sheet.addCell(cell0);
// 指定单元格位置(如:第一列第一行(0, 0))以及单元格内容为(如:小明)
for (int i = 0; i < heads.length; i++) {
Label cell = new Label(i, 1, heads[i]);
// 将定义好的单元格添加到工作表中
sheet.addCell(cell);
}
}
book.write();
} catch (Exception e) {
log.error("error", e);
} finally {
if (book != null) {
book.close();
}
if (os != null) {
os.close();
}
}
}
public static WritableWorkbook createMergeCellWorkBookWithStyle(OutputStream os, List dataList, String[] heads,
String[] headsStr, int[] columnStr, String headTitle) throws IOException, RowsExceededException, WriteException, IllegalAccessException,
InvocationTargetException, NoSuchMethodException {
// 根据数据大小具体分n个sheet页默认一页存储10000条数据
int sizeLoop = dataList.size();// 数据大小
int size = dataList.size();
if (sizeLoop < 10000) {
sizeLoop = 10000;
}
int sheetSize = 10000;
int loopSize = sizeLoop / sheetSize;
if (sizeLoop % sheetSize != 0) {
loopSize += 1;
}
// 设置样式
WritableFont wf_head = new WritableFont(WritableFont.ARIAL, 11, WritableFont.BOLD, false,
UnderlineStyle.NO_UNDERLINE, jxl.format.Colour.BLACK); // 定义格式 字体 下划线 斜体 粗体 颜色
WritableFont wf_table = new WritableFont(WritableFont.ARIAL, 10, WritableFont.NO_BOLD, false,
UnderlineStyle.NO_UNDERLINE, jxl.format.Colour.BLACK); // 定义格式 字体 下划线 斜体 粗体 颜色
WritableCellFormat wcf_head = new WritableCellFormat(wf_head); // 单元格定义
wcf_head.setAlignment(jxl.format.Alignment.CENTRE); // 设置对齐方式
wcf_head.setBorder(Border.ALL, BorderLineStyle.THIN, jxl.format.Colour.BLACK); // 边框
WritableCellFormat wcf_table = new WritableCellFormat(wf_table);
wcf_table.setAlignment(jxl.format.Alignment.CENTRE);
wcf_table.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);
wcf_table.setBorder(Border.ALL, BorderLineStyle.THIN, jxl.format.Colour.BLACK); // 边框
// 创建一个工作薄
WorkbookSettings workbookSettings = new WorkbookSettings();
workbookSettings.setEncoding("UTF-8"); // 解决中文乱
WritableWorkbook ws = Workbook.createWorkbook(os, workbookSettings);
// 分别往每个sheet页写数据
for (int l = 0; l < loopSize; l++) {
WritableSheet sheet = ws.createSheet("" + (l + 1) + "", l);
WritableFont wf_headt = new WritableFont(WritableFont.ARIAL, 20, WritableFont.BOLD, false,
UnderlineStyle.NO_UNDERLINE, jxl.format.Colour.BLACK);
WritableCellFormat wcf_head1 = new WritableCellFormat(wf_headt); // 单元格定义
wcf_head1.setAlignment(jxl.format.Alignment.CENTRE); // 设置对齐方式
sheet.mergeCells(0, 0, heads.length - 1, 0);
Label cell0 = new Label(0, 0, headTitle, wcf_head1);
sheet.addCell(cell0);
for (int i = 0; i < heads.length; i++) {
Label cell = new Label(i, 1, heads[i], wcf_head);
sheet.addCell(cell);
}
// 循环读取数据列表
int n = 2;
int allRows = 0;
for (int i = l * sheetSize; i < (l + 1) * sheetSize && i <= size - 1; i++) {
Object vrd = dataList.get(i);
for (int j = 0; j < headsStr.length; j++) {
Object value = PropertyUtils.getProperty(vrd, headsStr[j]);
if (value != null) {
sheet.setColumnView(j, value.toString().length() + 15);
sheet.addCell(new Label(j, n, value.toString(), wcf_table));
}
}
n++;
allRows++;
}
if (columnStr != null && columnStr.length > 0) {
sheet = mergeSameCell(sheet, Arrays.asList(ArrayUtils.toObject(columnStr)), allRows, 2);
}
}
return ws;
}
public static WritableSheet mergeSameCell(WritableSheet sheet, List<Integer> needMergeColNum, Integer allRows, Integer startMergeRowNum) throws WriteException {
List<MergeRecord> mergeRecords = new ArrayList<>();
//List<Integer> needMergeColNum = new ArrayList<>();
if (sheet != null && needMergeColNum != null) {
// 找出所有需要合并的单元格
for (Integer needCol : needMergeColNum) {
//Integer allRows = sheet.
String sameContent = null;
Integer firstRowNum = null;
Integer lastRowNum = null;
Integer firstColNum = null;
Integer lastColNum = null;
MergeRecord mergeRecord = null;
//sheet.getRows();
for (int rowNum = startMergeRowNum; rowNum < allRows + 1; rowNum++) {
//Cell[] cell=sheet.getRow(rowNum);
// 如果本行与下一行的值一样 ,则需要新建一个合并区域
//Row row = sheet.getRow(rowNum);
Cell[] row = sheet.getRow(rowNum);
Cell[] nextRow = sheet.getRow(rowNum + 1);
//Row nextRow = sheet.getRow(rowNum + 1);
//String cellVal = row.getCell(needCol).getStringCellValue();
String cellVal = row[needCol].getContents();
String nextCellVal = null;
if (nextRow != null) {
//nextCellVal = nextRow.getCell(needCol).getStringCellValue();
log.info("{}", nextRow.length);
if (nextRow.length > 0) {
nextCellVal = nextRow[needCol].getContents();
}
}
// 如果当行值等于相同值的话 合并行加1
if (sameContent != null && sameContent.equals(nextCellVal)) {
lastRowNum = rowNum + 1;
continue;
}
// 如果下一行的值与当前值不相同 或者已经到最后一行,那么结束本次的合并单元格任务
if (((sameContent != null && !sameContent.equals(nextCellVal))) || (nextRow == null && sameContent != null)) {
mergeRecord = new MergeRecord();
mergeRecord.setMergeContent(sameContent);
mergeRecord.setCulomnNum(needCol);
mergeRecord.setFirstRow(firstRowNum);
mergeRecord.setLastRow(lastRowNum);
mergeRecord.setFirstCol(firstColNum);
mergeRecord.setLastCol(lastColNum);
mergeRecords.add(mergeRecord);
// 将相同内容置空 ,并寻找下一个需要合并的单元格
sameContent = null;
}
// 如果第一次两个值一样的话
if (cellVal.equals(nextCellVal)) {
sameContent = cellVal;
firstRowNum = rowNum;
lastRowNum = rowNum + 1;
firstColNum = needCol;
lastColNum = needCol;
}
}
}
}
// 找完所有的单元格后 ,开始合并
for (MergeRecord mergeRecord : mergeRecords) {
//sheet.mergeCells(new CellRangeAddress(mergeRecord.getFirstRow(), mergeRecord.getLastRow(), mergeRecord.getFirstCol(), mergeRecord.getLastCol()));
sheet.mergeCells(mergeRecord.getFirstCol(), mergeRecord.getFirstRow(), mergeRecord.getLastCol(), mergeRecord.getLastRow());
}
return sheet;
}
}