一、創建工作簿並添加工作表
在Java中導出Excel,首先要創建一個工作簿,然後添加工作表,最後在工作表中添加內容。
示例代碼:
// 創建工作簿
Workbook workbook = new XSSFWorkbook();
// 創建工作表
Sheet sheet = workbook.createSheet("Sheet1");
二、合併單元格
生成的Excel表格可能需要合併單元格,例如合併表頭或者合併行或列。在Java中合併單元格非常簡單,只需指定需要合併的單元格的起始行、起始列、結束行、結束列即可。
示例代碼:
// 合併單元格 CellRangeAddress region = new CellRangeAddress(rowStart, rowEnd, colStart, colEnd); sheet.addMergedRegion(region);
三、設置單元格樣式
Java中可以通過設置單元格樣式來調整單元格的樣式,例如設置字體、顏色、對齊方式等。創建單元格樣式後,可以通過CellStyle應用到單元格中。
示例代碼:
// 創建單元格樣式
CellStyle cellStyle = workbook.createCellStyle();
cellStyle.setAlignment(HorizontalAlignment.CENTER);
cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
// 設置字體
Font font = workbook.createFont();
font.setFontName("宋體");
font.setFontHeightInPoints((short) 12);
font.setBold(true);
cellStyle.setFont(font);
// 應用樣式到單元格中
cell.setCellStyle(cellStyle);
四、寫入數據並導出
最後一步是向Excel表格中寫入數據,並將工作簿導出為Excel文件。
示例代碼:
// 向單元格中寫入數據
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue("Hello World");
// 導出Excel文件
FileOutputStream outputStream = new FileOutputStream("example.xlsx");
workbook.write(outputStream);
outputStream.close();
五、完整示例代碼
以下是一個完整的示例代碼,演示了如何創建工作簿、添加工作表、合併單元格、設置單元格樣式、向單元格中寫入數據並導出Excel文件。
import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
public class ExcelExporter {
public static void main(String[] args) throws Exception {
// 創建工作簿
Workbook workbook = new XSSFWorkbook();
// 創建工作表
Sheet sheet = workbook.createSheet("Sheet1");
// 合併單元格
CellRangeAddress region = new CellRangeAddress(0, 0, 0, 4);
sheet.addMergedRegion(region);
// 創建單元格樣式
CellStyle cellStyle = workbook.createCellStyle();
cellStyle.setAlignment(HorizontalAlignment.CENTER);
cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
// 設置字體
Font font = workbook.createFont();
font.setFontName("宋體");
font.setFontHeightInPoints((short) 16);
font.setBold(true);
cellStyle.setFont(font);
// 向單元格中寫入數據
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue("Hello World");
// 應用樣式到單元格中
cell.setCellStyle(cellStyle);
// 導出Excel文件
FileOutputStream outputStream = new FileOutputStream("example.xlsx");
workbook.write(outputStream);
outputStream.close();
}
}
原創文章,作者:AAMK,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/145868.html
微信掃一掃
支付寶掃一掃