POI 4.0读写Excel


POI 4.0了,尝试下

POI 4.0介绍

介绍

  • Apache POI 4.0.0 正式发布,不再支持 Java 6 与 7
  • Apache POI 4.0.0 发布了,此版本特点是一些新功能和众多 bug 修复,包括:
  • 删除了对 Java 6 和 7 的支持,使 Java 8 成为支持的最低版本
  • 需要新的 OOXML schema(1.4),因为不兼容的 XMLBeans 加载不再通过 POIXMLTypeLoader

参考

POI 4.1.0

maven

参考:Java 之 POI各Jar包作用

		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi</artifactId>
			<version>4.1.0</version>
		</dependency>
		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi-ooxml</artifactId>
			<version>4.1.0</version>
		</dependency>
		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi-ooxml-schemas</artifactId>
			<version>4.1.0</version>
		</dependency>

尝试代码

后缀名.xlsx

import java.io.FileOutputStream;

import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.CellUtil;
import org.apache.poi.ss.util.RegionUtil;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class CreateDemo2 {
	void create() {
		
		XSSFWorkbook workbook = new XSSFWorkbook();
		XSSFSheet sheet = workbook.createSheet("表1");
		CellRangeAddress region = new CellRangeAddress(1, 4, 2, 5);
		XSSFRow row = sheet.createRow(1);
		row.createCell(2).setCellValue("第二至五行3-6列合并");
		sheet.addMergedRegion(region);
		
		XSSFCellStyle cellStyle = workbook.createCellStyle();
        
        cellStyle.setBorderBottom(BorderStyle.THIN); // 下边框
        cellStyle.setBorderLeft(BorderStyle.THIN);// 左边框
        cellStyle.setBorderTop(BorderStyle.THIN);// 上边框
        cellStyle.setBorderRight(BorderStyle.THIN);// 右边框
        cellStyle.setAlignment(HorizontalAlignment.CENTER);// 水平居中

        XSSFFont font = workbook.createFont();
        font.setFontName("微软雅黑");// 设置字体名称
        font.setFontHeightInPoints((short) 10);// 设置字号
        font.setColor(IndexedColors.BLACK.index);// 设置字体颜色

        cellStyle.setFont(font);

        CellUtil.getCell(row, 2).setCellStyle(cellStyle);
        
        RegionUtil.setBorderBottom(BorderStyle.MEDIUM, region, sheet);
        RegionUtil.setBorderLeft(BorderStyle.MEDIUM, region, sheet);
        RegionUtil.setBorderRight(BorderStyle.MEDIUM, region, sheet);
        RegionUtil.setBorderTop(BorderStyle.MEDIUM, region, sheet);
        
        RegionUtil.setBottomBorderColor(IndexedColors.BLUE.index, region, sheet);
		RegionUtil.setLeftBorderColor(IndexedColors.BLUE.index, region, sheet);
		RegionUtil.setRightBorderColor(IndexedColors.BLUE.index, region, sheet);
		RegionUtil.setTopBorderColor(12, region, sheet);
        
        workbook.cloneSheet(0, "表2");
        
        FileOutputStream fileOut;
		try {
			fileOut = new FileOutputStream("D:\\a\\整机检测报告.xlsx");
			workbook.write(fileOut);
			fileOut.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println("写出成功!");
	}
}

后缀名.xls


import java.io.FileOutputStream;

import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.CellUtil;
import org.apache.poi.ss.util.RegionUtil;
import org.springframework.stereotype.Component;

@Component
public class CreateDemo {
	
	void create() {
		// 1.创建一个webbook,对应一个Excel文件
		HSSFWorkbook wb = new HSSFWorkbook();

		// 2.在建立的工作簿中添加一个sheet,对应Excell文件中的工作簿,并设置工作簿名称
		HSSFSheet sheet = wb.createSheet("我是工作簿左下角的名字(第一个)");

		// 2.1如果需要多个,则继续创建即可
		HSSFSheet sheet1 = wb.createSheet("我是工作簿左下角的名字(第二个)");

		// 3.第一行2,3,4列合并(注意:从0开始开始,参数分别表示起始第2行,结束第4行,起始第2列,结束第4列,大家可以
		// 在脑海中想象画出对应的矩形框)
		CellRangeAddress region1 = new CellRangeAddress(1, 4, 2, 5);
		HSSFRow row1 = sheet.createRow(1);

		// 第一个合并单元区域:
		// 3.1为合并单元格赋值,实际就是为坐标(1,1)这个单元格赋值(工作簿中坐标是(2,2))
		// 经本人测试,只有合并区域左上角那个单元格赋值能成功,左下角、右下角、右上角都不行。
		// 注意:这儿colum必须是 1 :因为这是代码,是从0开始数的,Excel中对应的是2,以下同理
		row1.createCell(2).setCellValue("第二至五行2-4列合并");
		// 4.把合并区域添加到工作簿中
		sheet.addMergedRegion(region1);

		// 5.设置合并单元格的边框样式,用RegionUtil这个工具类

		// 5.1设置合并单元格的边框是------or.........0r__________等等这样的样式
		RegionUtil.setBorderBottom(BorderStyle.THIN, region1, sheet);
		RegionUtil.setBorderLeft(BorderStyle.THIN, region1, sheet);
		RegionUtil.setBorderRight(BorderStyle.THIN, region1, sheet);
		RegionUtil.setBorderTop(BorderStyle.THIN, region1, sheet);

		// 5.2设置合并单元格边框的颜色
		RegionUtil.setBottomBorderColor(12, region1, sheet);
		RegionUtil.setLeftBorderColor(12, region1, sheet);
		RegionUtil.setRightBorderColor(12, region1, sheet);
		RegionUtil.setTopBorderColor(12, region1, sheet);

		// 6.创建单元格(单个cell)样式(为合并的单元格设置样式,设计上就是合并单元格的最左上角
		// 那个单元格设置样式,这儿坐标为(1.1),excel中为(2,2))这同时也是单个单元格的样式设置的代码
		HSSFCellStyle cellStyle = wb.createCellStyle();
		// 6.1创建字体样式对象
		Font fontStyle = wb.createFont();
		// 6.1.1字体加粗
		fontStyle.setBold(true);
		// 6.1.2字体大小
		fontStyle.setFontHeightInPoints((short) 12);
		// 7.将字体样式添加到单元格样式中
		cellStyle.setFont(fontStyle);
		// 6.2 单元格样式-->水平居中
		cellStyle.setAlignment(HorizontalAlignment.CENTER);
		// 6.3 单元格样式-->垂直居中
		cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
		// 6.4 单个cell边框样式
		cellStyle.setBorderBottom(BorderStyle.THIN);
		cellStyle.setBorderLeft(BorderStyle.THIN);
		cellStyle.setBorderRight(BorderStyle.THIN);
		cellStyle.setBorderTop(BorderStyle.THIN);
		// 6.4 单个cell框y、颜色
		cellStyle.setLeftBorderColor((short) 12);
		cellStyle.setBottomBorderColor((short) 12);
		cellStyle.setRightBorderColor((short) 12);
		cellStyle.setTopBorderColor((short) 12);

		// 7.得到坐标(1,1)Excel中(2,2)这个单元格cell对象,设置样式
		CellUtil.getCell(row1, 2).setCellStyle(cellStyle);

		FileOutputStream fileOut;
		try {
			fileOut = new FileOutputStream("D:\\a\\workbook.xls");
			wb.write(fileOut);
			fileOut.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println("写出成功!");
	}
}

POI 3.11实现

  • 原来使用POI 3.11实现的,导出为.xls格式。jar包只要引入poi-3.11-20141221.jar就可以了。

原来的代码

package cn.com.tcb.assembly.management.action.result.export;

import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.Map;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;

import cn.com.tcb.assembly.base.utils.GlobalVariable;

/**
 * @ClassName: ExcelExportor
 * @Description: 按照客户提供的指定格式导出excel文件
 */
public class ExcelExportor {
	private final static String[] HEADERS = { "OrderNum", "SerialNumber", "UnitSize", "StartTime", "EndTime", "Time",
			"GasketModel", "Gasket", "Result", "Abnormal", "Operator", "Assembly", "Date" };

	public void doExport(File file, List<Map<String, Object>> data) throws Exception {
		FileInputStream is = null;
		HSSFWorkbook workbook;
		try {
			is = new FileInputStream(file);
			workbook = new HSSFWorkbook(is);
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		} finally {
			close(is);
		}
		FileOutputStream os = null;
		try {
			os = new FileOutputStream(file);
			writeData2Workbook(workbook, data);
			workbook.write(os);
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		} finally {
			workbook.close();
			close(os);
		}
	}

	private static void close(Closeable stream) {
		if (stream != null) {
			try {
				stream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public void writeData2Workbook(HSSFWorkbook workbook, List<Map<String, Object>> data) {
		HSSFSheet sheet = workbook.getSheetAt(0);

		// 每个单元格格式
		HSSFCellStyle cellStyle = workbook.createCellStyle();
		HSSFFont font = workbook.createFont();
		cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN); // 下边框
		cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);// 左边框
		cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);// 上边框
		cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);// 右边框
		cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 水平居中

		font.setFontName("微软雅黑");// 设置字体名称
		font.setFontHeightInPoints((short) 10);// 设置字号
		font.setColor(HSSFColor.BLACK.index);// 设置字体颜色
		cellStyle.setFont(font);

		font.setFontName("黑体");
		font.setFontHeightInPoints((short) 16);// 设置字体大小
		for (int j = 0; j < data.size(); j++) {
			HSSFRow row = sheet.getRow(5 + j);
			if (row == null) {
				row = sheet.createRow(5 + j);
			}
			Map<String, Object> record = data.get(j);

			for (int i = 0; i < HEADERS.length; i++) {

				// 获得数据库每一列的值
				String val = String.valueOf(record.get(HEADERS[i]));
				if(val.equals("null")) {
					val = "";
				}

				int gasketModelArrayIndex = 0; // 垫片类型数组下标

				if (i < 6) {
					writeCell(i, val, cellStyle, row);
				}

				// 获得垫片类型,判断出属于哪一个类型,用下标gasketModelArrayIndex表示,
				// 单元格8个,顺序号:6-13,写入空值
				if (i == 6) {
					String[] gasketModelArray = GlobalVariable.GASKETMODEL;
					for (int k = 0; k < gasketModelArray.length; k++) {
						if((gasketModelArray[k].equals(val))) {
							gasketModelArrayIndex = k; // 匹配设置下标
						}
						writeCell(i + k, "", cellStyle, row);
					}
				}

				// 获得垫片值,写入正确序号的单元格
				if (i == 7) {
					writeCell(6 + gasketModelArrayIndex, val, cellStyle, row);
				}

				// 获得结果值,有6组12列数据.下表m=0-11,单元格顺序号:14-25
				if (i == 8) {
					String[] resultArray = val.split(",");
					for (int k = 0; k < resultArray.length; k++) {
						writeCell(14 + k, resultArray[k], cellStyle, row);
					}
				}

//				if(i >= 9) {
//					writeCell(i+17, val, cellStyle, row); // 打印异常一列
//				}

				if (i >= 10) {
					writeCell(i + 16, val, cellStyle, row); // 不打印异常一列
				}

			}
		}
	}

	private void writeCell(int i, String val, HSSFCellStyle cellStyle, HSSFRow row) {
		HSSFCell cell = row.getCell(i);
		if (cell == null) {
			cell = row.createCell(i);
		}
		cell.setCellValue(val);
		cell.setCellStyle(cellStyle);
	}
}

调用导出excel的代码

package cn.com.tcb.assembly.management.action.result;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.swing.JButton;
import javax.swing.filechooser.FileSystemView;

import cn.com.tcb.assembly.base.core.ui.PopupDialog;
import cn.com.tcb.assembly.base.core.ui.PopupManager;
import cn.com.tcb.assembly.management.action.result.export.ExcelExportor;
import cn.com.tcb.assembly.management.action.result.export.ExcelExportorXLSX;
import cn.com.tcb.assembly.management.action.result.export.ExportExcelProgressRate;
import cn.com.tcb.assembly.management.action.result.export.FileUtil;
import cn.com.tcb.assembly.management.action.result.export.Reader;
import cn.com.tcb.assembly.management.action.result.search.ISearch;
import cn.com.tcb.assembly.management.action.result.search.Search;
import cn.com.tcb.assembly.management.ui.result.ResultInfoFrame;

/**
 * 导出按钮事件
 */
public class ResultExportAction implements ActionListener {
	private ResultInfoFrame data;
	private ExportExcelProgressRate rate = new ExportExcelProgressRate();

	public ResultExportAction(ResultInfoFrame resultInfo) {
		this.data = resultInfo;
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		JButton button = (JButton) e.getSource();
		new Thread(new Runnable() {
			@Override
			public void run() {
				button.setEnabled(false);
				doAction();
				button.setEnabled(true);
			}
		}).start();

	}

	public void doAction() {
		//导出提示
		if(!optionDialog("确认导出?")){
			return;
		}
		
		// 模板文件路径
		String userDir = System.getProperty("user.dir");
		String temFilePath = userDir + "\\装配机测试结果.xlsx";

		// 导出文件路径,桌面,文件名,检测报告+当前日期时间
		SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");// 设置日期格式
		String dateTime = df.format(new Date());
		String fileName = "检测报告" + dateTime + ".xlsx";
		String Path = desktopPath() + "\\" + fileName;

		// 将模板文件复制到指定路径
		boolean copyFileSuccess = FileUtil.copyFile(temFilePath, Path, true);
		System.out.println("复制文件" + copyFileSuccess);

		if (copyFileSuccess != true) {
			return;
		}
		File file = new File(Path);
		// 显示进度条
		rate.setVisible(true);
		try {
			// 根据画面生成查询条件
			ISearch search = creatSearch();
			// 从数据库读取数据
			List<Map<String, Object>> data = new Reader(search, rate).doRead();
			// 数据写入文件
//			new ExcelExportor().doExport(file, data);
			new ExcelExportorXLSX().doExport(file, data);
			PopupManager.showMessageDialog("导出成功。文件" + file.getAbsolutePath());
		} catch (Exception e) {
			// e.printStackTrace();
			PopupManager.showMessageDialog("导出失败。" + e.getMessage());
		} finally {
			// 关闭进度条
			rate.setVisible(false);
			rate.dispose();
		}
	}

	/**
	 * @Title: creatSearch
	 * @Description: 获取界面用户输入,生成查询条件
	 * @return
	 */
	private ISearch creatSearch() {
		
		String option = (String) data.getComboBox().getSelectedItem();
		option = option.trim();
		
		String input = data.getInputField().getText();
		if((input.equals("") | input == null) && (!option.equals("全部"))) {
			PopupManager.showMessageDialog("请正确输入查询内容!");
			return null;
		}
		
		boolean time = false; 
		String start = "";
		String stop = "";
		if (data.getCheckBox_byDate().isSelected()) {
			time = true;
			start = getStartTime();
			stop = getStopTime();
		}
		
		boolean desc = data.getCheckBox_desc().isSelected();
		
		String operator = (getOperator() == null)? "":getOperator();
		String assembly = (getAssembly() == null)? "":getAssembly();
		String abnormal = (getAbnormal() == null)? "":getAbnormal();
		
		return new Search(option, input, time, start, stop, desc, operator, assembly, abnormal);
	}

	/**
	 * 获取日期查询时的开始时间
	 */
	private String getStartTime() {
		String dateStart = data.getTextField_startDate().getText();
		String hour = (String) data.getComboBox_startHour().getSelectedItem();
		String minute = (String) data.getComboBox_startMinute().getSelectedItem();
		if (Integer.parseInt(hour) < 10) {
			hour = "0" + hour;
		}
		if (Integer.parseInt(minute) < 10) {
			minute = "0" + minute;
		}
		String date = dateStart + " " + hour + ":" + minute + ":" + "00";
		return date;
	}

	/**
	 * 获取日期查询时的结束时间
	 */
	private String getStopTime() {
		String dateStart = data.getTextField_endDate().getText();
		String hour = (String) data.getComboBox_endHour().getSelectedItem();
		String minute = (String) data.getComboBox_endMinute().getSelectedItem();
		if (Integer.parseInt(hour) < 10) {
			hour = "0" + hour;
		}
		if (Integer.parseInt(minute) < 10) {
			minute = "0" + minute;
		}
		String date = dateStart + " " + hour + ":" + minute + ":" + "00";
		return date;
	}
	
	/**
	 * 获取是否按“操作员”作为查询条件
	 */
	private String getOperator() {
		if(data.getCheckBox_operator().isSelected()) {
			return (String) data.getComboBox_operator().getSelectedItem();
		}
		return "";
	}

	/**
	 * 获取是否按“装配机”作为查询条件
	 */
	private String getAssembly() {
		if(data.getCheckBox_assembly().isSelected()) {
			return (String) data.getComboBox_assembly().getSelectedItem();
		}
		return "";
	}
	
	/**
	 * 获取是否按“异常”作为查询条件
	 */
	private String getAbnormal() {
		if(data.getCheckBox_abnormal().isSelected()) {
			return (String) data.getComboBox_abnormal().getSelectedItem();
		}
		return "";
	}

	public String desktopPath() {
		// 当前用户桌面
		File desktopDir = FileSystemView.getFileSystemView().getHomeDirectory();
		String desktopPath = desktopDir.getAbsolutePath();
		return desktopPath;
	}
	
	/**
	 * @Title: optionDialog
	 * @Description: 选择弹窗,默认选择:是
	 */
	private boolean optionDialog(String message) {
		int i = PopupDialog.open(PopupManager.DEFAULT, "提醒窗口", message, new String[] { "是", "否" }, new int[] { 1, 2 },
				1, 2);
		if (i == 1) {
			return true;
		} else {
			return false;
		}
	}

}

POI 4.0实现

引用的jar包

  • 使用POI 4.0实现,导出格式为.xlsx

当时没用maven,现在只能一个一个添加jar包了

  • poi-4.0.0.jar
  • poi-ooxml-4.0.0.jar
  • poi-ooxml-schemas-4.0.0.jar

以及下载的POI自身实现引用的jar包

  • commons-codec-1.11.jar
  • commons-collections4-4.2.jar

额外还需要

  • xmlbeans-3.0.2.jar
  • commons-compress-1.18.jar

参考:Java 之 POI各Jar包作用

代码不同点

// POI 4.0的用法
IndexedColors.BLACK.index       // 单元格颜色
BorderStyle.THIN                // 单元格样式
HorizontalAlignment.CENTER      // 设置居中

// POI 3.11的用法
HSSFColor.BLACK.index           // 单元格颜色
HSSFCellStyle.BORDER_THIN       // 单元格样式
HSSFCellStyle.ALIGN_CENTER      // 设置居中

参考:POI 边框样式BorderStyle
参考:POI 颜色Color

代码

package cn.com.tcb.assembly.management.action.result.export;

import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.Map;

import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
	
import cn.com.tcb.assembly.base.utils.GlobalVariable;

/**
 * @ClassName: ExcelExportor
 * @Description: 按照客户提供的指定格式导出excel文件
 */
public class ExcelExportorXLSX {
	private final static String[] HEADERS = { "OrderNum", "SerialNumber", "UnitSize", "StartTime", "EndTime", "Time",
			"GasketModel", "Gasket", "Result", "Abnormal", "Operator", "Assembly", "Date" };

	public void doExport(File file, List<Map<String, Object>> data) throws Exception {
		FileInputStream is = null;
		XSSFWorkbook workbook;
		try {
			is = new FileInputStream(file);
			workbook = new XSSFWorkbook(is);
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		} finally {
			close(is);
		}
		FileOutputStream os = null;
		try {
			os = new FileOutputStream(file);
			writeData2Workbook(workbook, data);
			workbook.write(os);
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		} finally {
			workbook.close();
			close(os);
		}
	}

	private static void close(Closeable stream) {
		if (stream != null) {
			try {
				stream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public void writeData2Workbook(XSSFWorkbook workbook, List<Map<String, Object>> data) {
		XSSFSheet sheet = workbook.getSheetAt(0);

		// 每个单元格格式
		XSSFCellStyle cellStyle = workbook.createCellStyle();
		XSSFFont font = workbook.createFont();
		cellStyle.setBorderBottom(BorderStyle.THIN); // 下边框
		cellStyle.setBorderLeft(BorderStyle.THIN);// 左边框
		cellStyle.setBorderTop(BorderStyle.THIN);// 上边框
		cellStyle.setBorderRight(BorderStyle.THIN);// 右边框
		cellStyle.setAlignment(HorizontalAlignment.CENTER);// 水平居中

		font.setFontName("微软雅黑");// 设置字体名称
		font.setFontHeightInPoints((short) 10);// 设置字号
		font.setColor(IndexedColors.BLACK.index);// 设置字体颜色
		cellStyle.setFont(font);

		font.setFontName("黑体");
		font.setFontHeightInPoints((short) 16);// 设置字体大小
		for (int j = 0; j < data.size(); j++) {
			XSSFRow row = sheet.getRow(5 + j);
			if (row == null) {
				row = sheet.createRow(5 + j);
			}
			Map<String, Object> record = data.get(j);

			for (int i = 0; i < HEADERS.length; i++) {

				// 获得数据库每一列的值
				String val = String.valueOf(record.get(HEADERS[i]));
				if(val.equals("null")) {
					val = "";
				}

				int gasketModelArrayIndex = 0; // 垫片类型数组下标

				if (i < 6) {
					writeCell(i, val, cellStyle, row);
				}

				// 获得垫片类型,判断出属于哪一个类型,用下标gasketModelArrayIndex表示,
				// 单元格8个,顺序号:6-13,写入空值
				if (i == 6) {
					String[] gasketModelArray = GlobalVariable.GASKETMODEL;
					for (int k = 0; k < gasketModelArray.length; k++) {
						if((gasketModelArray[k].equals(val))) {
							gasketModelArrayIndex = k; // 匹配设置下标
						}
						writeCell(i + k, "", cellStyle, row);
					}
				}

				// 获得垫片值,写入正确序号的单元格
				if (i == 7) {
					writeCell(6 + gasketModelArrayIndex, val, cellStyle, row);
				}

				// 获得结果值,有6组12列数据.下表m=0-11,单元格顺序号:14-25
				if (i == 8) {
					String[] resultArray = val.split(",");
					for (int k = 0; k < resultArray.length; k++) {
						writeCell(14 + k, resultArray[k], cellStyle, row);
					}
				}

//				if(i >= 9) {
//					writeCell(i+17, val, cellStyle, row); // 打印异常一列
//				}

				if (i >= 10) {
					writeCell(i + 16, val, cellStyle, row); // 不打印异常一列
				}

			}
		}
	}

	private void writeCell(int i, String val, XSSFCellStyle cellStyle, XSSFRow row) {
		XSSFCell cell = row.getCell(i);
		if (cell == null) {
			cell = row.createCell(i);
		}
		cell.setCellValue(val);
		cell.setCellStyle(cellStyle);
	}
}

错误代码

java.lang.ClassNotFoundException: org.apache.xmlbeans.XmlException

原因:查找资料了解到 是因为官方包里默认是不包含xmlbean.jar包的,需要自己添加xmlbeans.jar这个包,下载地址

Caused by: java.lang.ClassNotFoundException: org.apache.commons.compress.archivers.zip.ZipFile

原因:显然还是缺少包的引用:commons-compress-1.18.jar,下载地址
参考:https://www.jianshu.com/p/f6256b9d8bcc

The supplied data appears to be in the OLE2 Format. You are calling the part of POI that deals with OOXML (Office Open XML) Documents. You need to call a different part of POI to process this data (eg HSSF instead of XSSF)

原因:原来是.xls,导出文件格式没改成.xlsx,低级失误


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM