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