我是靠谱客的博主 迷路山水,最近开发中收集的这篇文章主要介绍JAVA POI自动导出数据和图片到excel(单元格合并)JAVA POI自动导出数据和图片到excel(单元格合并),觉得挺不错的,现在分享给大家,希望可以做个参考。
概述
JAVA POI自动导出数据和图片到excel(单元格合并)
参考链接:
POI XSSFWorkbook读取网络中的图片资源导入EXCEL中
controller
@PostMapping("/exportExcel")
public void exportExcel(@RequestBody ApprovalRequest request, HttpServletResponse response) throws Exception {
String fileName = "待审批数据";
List<WaitApprovalResponse> data = queryWaitApprovalList(request,total);
auditWaitDataExport(fileName,data,response);
}
/**
* 待审批导出
* @param response
* @param data
*/
private void auditWaitDataExport(String fileName, List<WaitApprovalResponse> data, HttpServletResponse response ) {
String titleColumn[] = new String[]{"systemId", "submitterName", "submissionDate",
"chospitalName","caddress","clocationName","clocationNotes","cimages",
"ohospitalName","oaddress","olocationName","olocationNotes","oimages",
"comments","approvalStatus"};
String firstTitleName[] = new String[]{"Sys ID", "提交人", "提交时间", "更改值","","","","","原始值","","","","","备注","审批"};
String secondTitleName[] = new String[]{"#", "#", "#", "名称","地址","备注1","备注2","设备图片",
"名称","地址","备注1","备注2","设备图片","#","#"};
int titleSize[] = new int[]{20,20,20,20,20,20,20,20,20,20,20,20,20,20,20};
ExcelExport excelExport = new ExcelExport();
excelExport.auditWaitDataExport(response,fileName,titleColumn,firstTitleName,secondTitleName,titleSize , data);
}
util
package cn.com.ge.apm.util;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFPalette;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.CellUtil;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.apache.poi.xssf.usermodel.XSSFDrawing;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.lang.reflect.Method;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
/**
* @Author: yyl
* @Description: excel导出轮子
* @Date: Created in 2020/10/16
*/
public class ExcelExport {
private static final Logger logger = LoggerFactory.getLogger(ExcelExport.class);
HttpServletResponse response;
// 文件名
private String fileName;
//文件保存路径
private String fileDir;
//sheet名
private String sheetName;
//表头字体
private String titleFontType = "Arial Unicode MS";
//表头背景色
private String titleBackColor = "C1FBEE";
//表头字号
private short titleFontSize = 12;
//添加自动筛选的列 如 A:M
private String address = "";
//正文字体
private String contentFontType = "Arial Unicode MS";
//正文字号
private short contentFontSize = 12;
//Float类型数据小数位
private String floatDecimal = "0.00";
//Double类型数据小数位
private String doubleDecimal = "0.00";
//设置列的公式
private String colFormula[] = null;
DecimalFormat floatDecimalFormat = new DecimalFormat(floatDecimal);
DecimalFormat doubleDecimalFormat = new DecimalFormat(doubleDecimal);
private HSSFWorkbook workbook = null;
public ExcelExport() {
}
public ExcelExport(String fileDir, String sheetName) {
this.fileDir = fileDir;
this.sheetName = sheetName;
workbook = new HSSFWorkbook();
}
public ExcelExport(HttpServletResponse response, String fileName, String sheetName) {
this.fileName = fileName;
this.response = response;
this.sheetName = sheetName;
workbook = new HSSFWorkbook();
}
/**
* 设置表头字体.
*
* @param titleFontType
*/
public void setTitleFontType(String titleFontType) {
this.titleFontType = titleFontType;
}
/**
* 设置表头背景色.
*
* @param titleBackColor 十六进制
*/
public void setTitleBackColor(String titleBackColor) {
this.titleBackColor = titleBackColor;
}
/**
* 设置表头字体大小.
*
* @param titleFontSize
*/
public void setTitleFontSize(short titleFontSize) {
this.titleFontSize = titleFontSize;
}
/**
* 设置表头自动筛选栏位,如A:AC.
*
* @param address
*/
public void setAddress(String address) {
this.address = address;
}
/**
* 设置正文字体.
*
* @param contentFontType
*/
public void setContentFontType(String contentFontType) {
this.contentFontType = contentFontType;
}
/**
* 设置正文字号.
*
* @param contentFontSize
*/
public void setContentFontSize(short contentFontSize) {
this.contentFontSize = contentFontSize;
}
/**
* 设置float类型数据小数位 默认.00
*
* @param doubleDecimal 如 ".00"
*/
public void setDoubleDecimal(String doubleDecimal) {
this.doubleDecimal = doubleDecimal;
}
/**
* 设置doubel类型数据小数位 默认.00
*
* @param floatDecimalFormat 如 ".00
*/
public void setFloatDecimalFormat(DecimalFormat floatDecimalFormat) {
this.floatDecimalFormat = floatDecimalFormat;
}
/**
* 设置列的公式
*
* @param colFormula 存储i-1列的公式 涉及到的行号使用@替换 如A@+B@
*/
public void setColFormula(String[] colFormula) {
this.colFormula = colFormula;
}
/**
* 写excel.
* xls方式
*
* @param titleColumn 对应bean的属性名
* @param titleName excel要导出的列名
* @param titleSize 列宽
* @param dataList 数据
*/
public void writeExcel(String titleColumn[], String titleName[], int titleSize[], List<?> dataList) {
//添加Worksheet(不添加sheet时生成的xls文件打开时会报错)
Sheet sheet = workbook.createSheet(this.sheetName);
//新建文件
OutputStream out = null;
try {
if (fileDir != null) {
//有文件路径
out = new FileOutputStream(fileDir);
} else {
//否则,直接写到输出流中
out = response.getOutputStream();
fileName = fileName + ".xls";
response.setContentType("application/msexcel;charset=UTF-8");
response.setHeader("Content-Disposition", "attachment; filename="
+ URLEncoder.encode(fileName, "UTF-8"));
}
//写入excel的表头
Row titleNameRow = workbook.getSheet(sheetName).createRow(0);
//设置样式
CellStyle titleStyle = workbook.createCellStyle();
titleStyle = (HSSFCellStyle) setFontAndBorder(titleStyle, titleFontType, (short) titleFontSize);
titleStyle = (HSSFCellStyle) setColor(titleStyle, titleBackColor, (short) 10);
for (int i = 0; i < titleName.length; i++) {
sheet.setColumnWidth(i, titleSize[i] * 256); //设置宽度
Cell cell = titleNameRow.createCell(i);
cell.setCellStyle(titleStyle);
cell.setCellValue(titleName[i].toString());
}
//为表头添加自动筛选
if (!"".equals(address)) {
CellRangeAddress c = (CellRangeAddress) CellRangeAddress.valueOf(address);
sheet.setAutoFilter(c);
}
//通过反射获取数据并写入到excel中
if (dataList != null && dataList.size() > 0) {
//设置样式
HSSFCellStyle dataStyle = workbook.createCellStyle();
titleStyle = (HSSFCellStyle) setFontAndBorder(titleStyle, contentFontType, (short) contentFontSize);
if (titleColumn.length > 0) {
for (int rowIndex = 1; rowIndex <= dataList.size(); rowIndex++) {
Object obj = dataList.get(rowIndex - 1); //获得该对象
Class clsss = obj.getClass(); //获得该对对象的class实例
Row dataRow = workbook.getSheet(sheetName).createRow(rowIndex);
for (int columnIndex = 0; columnIndex < titleColumn.length; columnIndex++) {
String title = titleColumn[columnIndex].toString().trim();
if (!"".equals(title)) { //字段不为空
//使首字母大写
String UTitle = Character.toUpperCase(title.charAt(0)) + title.substring(1, title.length()); // 使其首字母大写;
String methodName = "get" + UTitle;
// 设置要执行的方法
Method method = clsss.getDeclaredMethod(methodName);
//获取返回类型
String returnType = method.getReturnType().getName();
Object object = method.invoke(obj);
String data = method.invoke(obj) == null ? "" : object.toString();
Cell cell = dataRow.createCell(columnIndex);
if (data != null && !"".equals(data)) {
if ("int".equals(returnType)) {
cell.setCellValue(Integer.parseInt(data));
} else if ("long".equals(returnType)) {
cell.setCellValue(Long.parseLong(data));
} else if ("float".equals(returnType)) {
cell.setCellValue(floatDecimalFormat.format(Float.parseFloat(data)));
} else if ("double".equals(returnType)) {
cell.setCellValue(doubleDecimalFormat.format(Double.parseDouble(data)));
} else if (Date.class.getName().equals(returnType)) {
cell.setCellValue(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(object));
} else {
cell.setCellValue(data);
}
}
} else { //字段为空 检查该列是否是公式
if (colFormula != null) {
String sixBuf = colFormula[columnIndex].replace("@", (rowIndex + 1) + "");
Cell cell = dataRow.createCell(columnIndex);
cell.setCellFormula(sixBuf);
}
}
}
}
}
}
workbook.write(out);
} catch (Exception e) {
e.printStackTrace();
}finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
logger.debug("导出写Excel异常");
}
}
}
}
/**
* xlsx方式
*
* @param response
* @param fileName
* @param titleColumn
* @param titleName
* @param titleSize
* @param dataList
*/
public void writeBigExcel(HttpServletResponse response, String fileName, String titleColumn[],
String titleName[], int titleSize[], List<?> dataList) {
try {
SXSSFWorkbook workbook = new SXSSFWorkbook(100);
OutputStream out = response.getOutputStream();
String lastFileName = fileName + ".xlsx";
response.setContentType("application/msexcel;charset=UTF-8");
response.setHeader("Content-Disposition", "attachment; filename="
+ URLEncoder.encode(lastFileName, "UTF-8"));
int k = 0;
int rowIndex;
Sheet sheet = workbook.createSheet(fileName + (k + 1));
//写入excel的表头
Row titleNameRow = workbook.getSheet(fileName + (k + 1)).createRow(0);
for (int i = 0; i < titleName.length; i++) {
sheet.setColumnWidth(i, titleSize[i] * 256); //设置宽度
Cell cell = titleNameRow.createCell(i);
cell.setCellValue(titleName[i]);
}
//写入到excel中
if (dataList != null && dataList.size() > 0) {
if (titleColumn.length > 0) {
for (int index = 0; index < dataList.size(); index++) {
//每个sheet3W条数据
if (index != 0 && (index) % 30000 == 0) {
k = k + 1;
sheet = workbook.createSheet(fileName + (k + 1));
//写入excel的表头
titleNameRow = workbook.getSheet(fileName + (k + 1)).createRow(0);
for (int i = 0; i < titleName.length; i++) {
sheet.setColumnWidth(i, titleSize[i] * 256); //设置宽度
Cell cell = titleNameRow.createCell(i);
cell.setCellValue(titleName[i]);
}
}
if (index < 30000) {
rowIndex = index + 1;
} else {
rowIndex = index - 30000 * ((index) / 30000) + 1;
}
Object obj = dataList.get(index);
Class clazz = obj.getClass();
Row dataRow = workbook.getSheet(fileName + (k + 1)).createRow(rowIndex);
for (int columnIndex = 0; columnIndex < titleColumn.length; columnIndex++) {
String title = titleColumn[columnIndex].trim();
if (!"".equals(title)) {
// 获取返回类型
String UTitle = Character.toUpperCase(title.charAt(0)) + title.substring(1, title.length()); // 使其首字母大写;
String methodName = "get" + UTitle;
Method method = clazz.getDeclaredMethod(methodName);
String returnType = method.getReturnType().getName();
Object object = method.invoke(obj);
String data = method.invoke(obj) == null ? "" : object.toString();
Cell cell = dataRow.createCell(columnIndex);
if (data != null && !"".equals(data)) {
if ("int".equals(returnType)) {
cell.setCellValue(Integer.parseInt(data));
} else if ("long".equals(returnType)) {
cell.setCellValue(Long.parseLong(data));
} else if ("float".equals(returnType)) {
cell.setCellValue(new DecimalFormat("0.00").format(Float.parseFloat(data)));
} else if ("double".equals(returnType)) {
cell.setCellValue(new DecimalFormat("0.00").format(Double.parseDouble(data)));
} else if (Date.class.getName().equals(returnType)) {
cell.setCellValue(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(object));
} else {
cell.setCellValue(data);
}
} else { //字段为空 检查该列是否是公式
if (colFormula != null) {
String sixBuf = colFormula[columnIndex].replace("@", (rowIndex + 1) + "");
cell = dataRow.createCell(columnIndex);
cell.setCellFormula(sixBuf);
}
}
}
}
}
}
}
workbook.write(out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 将16进制的颜色代码写入样式中来设置颜色
*
* @param style 保证style统一
* @param color 颜色:66FFDD
* @param index 索引 8-64 使用时不可重复
* @return
*/
public CellStyle setColor(CellStyle style, String color, short index) {
if ("".equals(color)) {
//转为RGB码
int r = Integer.parseInt((color.substring(0, 2)), 16); //转为16进制
int g = Integer.parseInt((color.substring(2, 4)), 16);
int b = Integer.parseInt((color.substring(4, 6)), 16);
//自定义cell颜色
HSSFPalette palette = workbook.getCustomPalette();
palette.setColorAtIndex((short) index, (byte) r, (byte) g, (byte) b);
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
style.setFillForegroundColor(index);
}
return style;
}
/**
* 设置字体并加外边框
*
* @param style 样式
* @param style 字体名
* @param style 大小
* @return
*/
public CellStyle setFontAndBorder(CellStyle style, String fontName, short size) {
HSSFFont font = workbook.createFont();
font.setFontHeightInPoints(size);
font.setFontName(fontName);
font.setBold(true);
style.setFont(font);
style.setBorderBottom(BorderStyle.THIN); //下边框
style.setBorderLeft(BorderStyle.THIN);//左边框
style.setBorderTop(BorderStyle.THIN);//上边框
style.setBorderRight(BorderStyle.THIN);//右边框
return style;
}
/**
* 待审批导出
*/
public void auditWaitDataExport(HttpServletResponse response, String fileName, String titleColumn[],
String firstTitleName[],String secondTitleName[], int titleSize[], List<?> dataList) {
try {
XSSFWorkbook workbook = new XSSFWorkbook();
OutputStream out = response.getOutputStream();
String lastFileName = fileName + ".xlsx";
response.setContentType("application/msexcel;charset=UTF-8");
response.setHeader("Content-Disposition", "attachment; filename="
+ URLEncoder.encode(lastFileName, "UTF-8"));
int k = 0;
int rowIndex;
XSSFSheet sheet = workbook.createSheet(fileName + (k + 1));
//画图的顶级管理器,一个sheet只能获取一个(一定要注意这点)
XSSFDrawing patriarch = sheet.createDrawingPatriarch();
//写入excel的第一行表头
CellRangeAddress region1 = new CellRangeAddress(0, 0, 3, 7);
CellRangeAddress region2 = new CellRangeAddress(0, 0, 8, 12);
sheet.addMergedRegion(region1);
sheet.addMergedRegion(region2);
Row titleNameRow = workbook.getSheet(fileName + (k + 1)).createRow(0);
for (int i = 0; i < firstTitleName.length; i++) {
sheet.setColumnWidth(i, titleSize[i] * 256); //设置宽度
Cell cell = titleNameRow.createCell(i);
cell.setCellValue(firstTitleName[i]);
setTableHeadStyle(workbook, cell);
}
//写入excel的第二行表头
Row secondTitleRow = workbook.getSheet(fileName + (k + 1)).createRow(1);
for (int i = 0; i < secondTitleName.length; i++) {
sheet.setColumnWidth(i, titleSize[i] * 256); //设置宽度
Cell cell = secondTitleRow.createCell(i);
if(!"#".equals(secondTitleName[i])){
cell.setCellValue(secondTitleName[i]);
setTableHeadStyle(workbook, cell);
}
}
//写入到excel中
if (dataList != null && dataList.size() > 0) {
if (titleColumn.length > 0) {
for (int index = 0; index < dataList.size(); index++) {
//每个sheet3W条数据
if (index != 0 && (index) % 30000 == 0) {
k = k + 1;
sheet = workbook.createSheet(fileName + (k + 1));
CellRangeAddress region3 = new CellRangeAddress(0, 0, 3, 7);
CellRangeAddress region4 = new CellRangeAddress(0, 0, 8, 12);
sheet.addMergedRegion(region3);
sheet.addMergedRegion(region4);
//写入excel的表头
titleNameRow = workbook.getSheet(fileName + (k + 1)).createRow(0);
for (int i = 0; i < firstTitleName.length; i++) {
sheet.setColumnWidth(i, titleSize[i] * 256); //设置宽度
Cell cell = titleNameRow.createCell(i);
cell.setCellValue(firstTitleName[i]);
}
//写入excel的第二行表头
secondTitleRow = workbook.getSheet(fileName + (k + 1)).createRow(1);
for (int i = 0; i < secondTitleName.length; i++) {
sheet.setColumnWidth(i, titleSize[i] * 256); //设置宽度
Cell cell = secondTitleRow.createCell(i);
if(!"#".equals(secondTitleName[i])){
cell.setCellValue(secondTitleName[i]);
}
}
}
if (index < 30000) {
rowIndex = index + 2;
} else {
rowIndex = index - 30000 * ((index) / 30000) + 2;
}
Object obj = dataList.get(index);
Class clazz = obj.getClass();
Row dataRow = workbook.getSheet(fileName + (k + 1)).createRow(rowIndex);
dataRow.setHeight((short)(256*15));//设置行高
for (int columnIndex = 0; columnIndex < titleColumn.length; columnIndex++) {
String title = titleColumn[columnIndex].trim();
if (!"".equals(title)) {
// 获取返回类型
String UTitle = Character.toUpperCase(title.charAt(0)) + title.substring(1, title.length()); // 使其首字母大写;
String methodName = "get" + UTitle;
Method method = clazz.getDeclaredMethod(methodName);
String returnType = method.getReturnType().getName();
Object object = method.invoke(obj);
if("getCimages".equals(methodName)){
String[] data = (String[]) method.invoke(obj);
if(data !=null && data.length>0){
String url = data[0];
if(StringUtils.isEmpty(url)){
continue;
}
byte[] bytes = downloadImage(url);
if(bytes!=null){
insertImage(index,workbook,patriarch,bytes,columnIndex,rowIndex);
}
}
}else {
String data = method.invoke(obj) == null ? "" : object.toString();
Cell cell = dataRow.createCell(columnIndex);
if (data != null && !"".equals(data)) {
if ("int".equals(returnType)) {
cell.setCellValue(Integer.parseInt(data));
} else if ("long".equals(returnType)) {
cell.setCellValue(Long.parseLong(data));
} else if ("float".equals(returnType)) {
cell.setCellValue(new DecimalFormat("0.00").format(Float.parseFloat(data)));
} else if ("double".equals(returnType)) {
cell.setCellValue(new DecimalFormat("0.00").format(Double.parseDouble(data)));
} else if (Date.class.getName().equals(returnType)) {
cell.setCellValue(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(object));
} else {
cell.setCellValue(data);
}
} else { //字段为空 检查该列是否是公式
if (colFormula != null) {
String sixBuf = colFormula[columnIndex].replace("@", (rowIndex + 1) + "");
cell = dataRow.createCell(columnIndex);
cell.setCellFormula(sixBuf);
}
}
}
}
}
}
}
}
workbook.write(out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private void insertImage(int index,XSSFWorkbook workbook, XSSFDrawing patriarch,byte[] byteData,int colIndex,int rowIndex) {
/**anchor主要用于设置图片的属性
* 该构造函数有8个参数
* 前四个参数是控制图片在单元格的位置,分别是图片距离单元格left,top,right,bottom的像素距离
* 后四个参数,前两个表示图片左上角所在的cellNum和 rowNum,后两个参数对应的表示图片右下角所在的cellNum和 rowNum,
* excel中的cellNum和rowNum的index都是从0开始的
*
*/
XSSFClientAnchor anchor = new XSSFClientAnchor(0, 0, 0, 0, (short)colIndex, rowIndex, (short) colIndex+1,rowIndex+1 );
//Sets the anchor type (图片在单元格的位置)
//0 = Move and size with Cells, 2 = Move but don't size with cells, 3 = Don't move or size with cells.
anchor.setAnchorType(ClientAnchor.AnchorType.MOVE_AND_RESIZE);//设置图片随单元移动调整大小
patriarch.createPicture(anchor, workbook.addPicture(byteData, XSSFWorkbook.PICTURE_TYPE_JPEG));
}
private void setTableHeadStyle(XSSFWorkbook workbook, Cell cell) {
CellStyle style = workbook.createCellStyle();
//设置字体
Font font = workbook.createFont();
font.setFontName("黑体");
font.setFontHeightInPoints((short) 12);//设置字体大小
font.setBold(true);
style.setFont(font);
//设置背景色
// style.setFillForegroundColor(IndexedColors.AQUA.getIndex());
// style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
cell.setCellStyle(style);
// 设置单元格内容水平垂直居中
CellUtil.setAlignment(cell, HorizontalAlignment.CENTER);
CellUtil.setVerticalAlignment(cell, VerticalAlignment.CENTER);
}
/**
* 审批历史导出
*/
public void auditFinishDataExport(HttpServletResponse response, String fileName, String titleColumn[],
String firstTitleName[],String secondTitleName[], int titleSize[], List<?> dataList) {
try {
SXSSFWorkbook workbook = new SXSSFWorkbook(100);
OutputStream out = response.getOutputStream();
String lastFileName = fileName + ".xlsx";
response.setContentType("application/msexcel;charset=UTF-8");
response.setHeader("Content-Disposition", "attachment; filename="
+ URLEncoder.encode(lastFileName, "UTF-8"));
int k = 0;
int rowIndex;
Sheet sheet = workbook.createSheet(fileName + (k + 1));
//写入excel的第一行表头
CellRangeAddress region1 = new CellRangeAddress(0, 0, 3, 7);
sheet.addMergedRegion(region1);
Row titleNameRow = workbook.getSheet(fileName + (k + 1)).createRow(0);
for (int i = 0; i < firstTitleName.length; i++) {
sheet.setColumnWidth(i, titleSize[i] * 256); //设置宽度
Cell cell = titleNameRow.createCell(i);
cell.setCellValue(firstTitleName[i]);
// 设置单元格内容水平垂直居中
CellUtil.setAlignment(cell, HorizontalAlignment.CENTER);
CellUtil.setVerticalAlignment(cell, VerticalAlignment.CENTER);
//生成单元格样式
CellStyle style = workbook.createCellStyle();
//设置背景颜色
style.setFillForegroundColor(IndexedColors.CORNFLOWER_BLUE.getIndex());// 设置背景色
cell.setCellStyle(style);
}
//写入excel的第二行表头
Row secondTitleRow = workbook.getSheet(fileName + (k + 1)).createRow(1);
for (int i = 0; i < secondTitleName.length; i++) {
sheet.setColumnWidth(i, titleSize[i] * 256); //设置宽度
Cell cell = secondTitleRow.createCell(i);
if(!"#".equals(secondTitleName[i])){
cell.setCellValue(secondTitleName[i]);
}
}
//写入到excel中
if (dataList != null && dataList.size() > 0) {
if (titleColumn.length > 0) {
for (int index = 0; index < dataList.size(); index++) {
//每个sheet3W条数据
if (index != 0 && (index) % 30000 == 0) {
k = k + 1;
sheet = workbook.createSheet(fileName + (k + 1));
CellRangeAddress region3 = new CellRangeAddress(0, 0, 3, 7);
sheet.addMergedRegion(region3);
//写入excel的表头
titleNameRow = workbook.getSheet(fileName + (k + 1)).createRow(0);
for (int i = 0; i < firstTitleName.length; i++) {
sheet.setColumnWidth(i, titleSize[i] * 256); //设置宽度
Cell cell = titleNameRow.createCell(i);
cell.setCellValue(firstTitleName[i]);
}
//写入excel的第二行表头
secondTitleRow = workbook.getSheet(fileName + (k + 1)).createRow(1);
for (int i = 0; i < secondTitleName.length; i++) {
sheet.setColumnWidth(i, titleSize[i] * 256); //设置宽度
Cell cell = secondTitleRow.createCell(i);
if(!"#".equals(secondTitleName[i])){
cell.setCellValue(secondTitleName[i]);
}
}
}
if (index < 30000) {
rowIndex = index + 2;
} else {
rowIndex = index - 30000 * ((index) / 30000) + 2;
}
Object obj = dataList.get(index);
Class clazz = obj.getClass();
Row dataRow = workbook.getSheet(fileName + (k + 1)).createRow(rowIndex);
for (int columnIndex = 0; columnIndex < titleColumn.length; columnIndex++) {
String title = titleColumn[columnIndex].trim();
if (!"".equals(title)) {
// 获取返回类型
String UTitle = Character.toUpperCase(title.charAt(0)) + title.substring(1, title.length()); // 使其首字母大写;
String methodName = "get" + UTitle;
Method method = clazz.getDeclaredMethod(methodName);
String returnType = method.getReturnType().getName();
Object object = method.invoke(obj);
String data = method.invoke(obj) == null ? "" : object.toString();
Cell cell = dataRow.createCell(columnIndex);
if (data != null && !"".equals(data)) {
if ("int".equals(returnType)) {
cell.setCellValue(Integer.parseInt(data));
} else if ("long".equals(returnType)) {
cell.setCellValue(Long.parseLong(data));
} else if ("float".equals(returnType)) {
cell.setCellValue(new DecimalFormat("0.00").format(Float.parseFloat(data)));
} else if ("double".equals(returnType)) {
cell.setCellValue(new DecimalFormat("0.00").format(Double.parseDouble(data)));
} else if (Date.class.getName().equals(returnType)) {
cell.setCellValue(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(object));
} else {
cell.setCellValue(data);
}
} else { //字段为空 检查该列是否是公式
if (colFormula != null) {
String sixBuf = colFormula[columnIndex].replace("@", (rowIndex + 1) + "");
cell = dataRow.createCell(columnIndex);
cell.setCellFormula(sixBuf);
}
}
}
}
}
}
}
workbook.write(out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 下载图片
* @param pictureUrl
* @return
*/
public byte[] downloadImage(String pictureUrl){
try{
// pictureUrl = pictureUrl.replaceAll(" ","");
// if ( !(pictureUrl.startsWith("http")) && !(pictureUrl.startsWith("https"))){
// int indexOf = pictureUrl.indexOf("//");
// String endStr = pictureUrl.substring(indexOf);
// pictureUrl = "http:"+endStr;
//
// }
URL url = new URL(pictureUrl);
//打开链接
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
//设置请求方式为"GET"
conn.setRequestMethod("GET");
//超时响应时间为50秒
conn.setConnectTimeout(50 * 1000);
//通过输入流获取图片数据
InputStream inStream = conn.getInputStream();
//得到图片的二进制数据,以二进制封装得到数据,具有通用性
byte[] byteData = readInputStream(inStream);
return byteData;
}catch (Exception e){
logger.error("downloadImage error",e);
}
return null;
}
private static byte[] readInputStream(InputStream inStream) throws Exception{
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
//创建一个Buffer字符串
byte[] buffer = new byte[1024];
//每次读取的字符串长度,如果为-1,代表全部读取完毕
int len = 0;
//使用一个输入流从buffer里把数据读取出来
while( (len=inStream.read(buffer)) != -1 ){
//用输出流往buffer里写入数据,中间参数代表从哪个位置开始读,len代表读取的长度
outStream.write(buffer, 0, len);
}
//关闭输入流
inStream.close();
//把outStream里的数据写入内存
return outStream.toByteArray();
}
}
最后
以上就是迷路山水为你收集整理的JAVA POI自动导出数据和图片到excel(单元格合并)JAVA POI自动导出数据和图片到excel(单元格合并)的全部内容,希望文章能够帮你解决JAVA POI自动导出数据和图片到excel(单元格合并)JAVA POI自动导出数据和图片到excel(单元格合并)所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复