SpringBootWeb 篇-入门了解 Apache POI 使用方法
    		       		warning:
    		            这篇文章距离上次修改已过420天,其中的内容可能已经有所变动。
    		        
        		                
                Apache POI 是处理 Microsoft Office 文件的开源 Java 库,支持 Excel、Word 和 PowerPoint 文件的读写操作。以下是使用 Apache POI 创建和写入 Excel 文件的示例代码:
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
 
import java.io.FileOutputStream;
import java.io.IOException;
 
public class ExcelExample {
    public static void main(String[] args) {
        // 创建一个新的工作簿
        Workbook workbook = new XSSFWorkbook();
        // 创建一个工作表(sheet)
        Sheet sheet = workbook.createSheet("ExampleSheet");
 
        // 创建行(0基索引)
        Row row = sheet.createRow(0);
 
        // 创建单元格并设置值
        Cell cell = row.createCell(0);
        cell.setCellValue("Hello");
        cell = row.createCell(1);
        cell.setCellValue("World");
 
        // 写入到文件
        try (FileOutputStream outputStream = new FileOutputStream("example.xlsx")) {
            workbook.write(outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 清理资源
            try {
                workbook.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}这段代码创建了一个名为 "example.xlsx" 的 Excel 文件,并在其中写入了一行文本数据 "Hello" 和 "World"。代码使用 try-with-resources 确保 FileOutputStream 和 Workbook 资源在操作完成后正确关闭,以防止资源泄露。
评论已关闭