首页 > 编程语言 >在Java中使用Apache POI导入导出Excel(一)

在Java中使用Apache POI导入导出Excel(一)

时间:2024-12-01 14:31:09浏览次数:11  
标签:Java wb Excel cell createCell POI new sheet row

Excel导入导出应用场景

在日常的管理系统应用场景中,进行Excel表格的导入导出是比较常见的需求,比如电商平台、企业管理系统、库存管理系统、人事管理系统等等,基本都需要使用数据进行分析,需要将已有的数据通过Excel导入到系统中,或者将系统分析的结果导出到Excel文件中,可以说在这些系统中,Excel导入导出是一个重要且普遍使用的功能,本文将介绍在Java开发中,如何快速实现Excel的导入导出。

Apache POI介绍

为了在Java中实现Excel的导入导出,我们一般会用到Apache的一个重要组件Apache POI,Apache POI是用Java编写的免费开源的跨平台的 Java API,Apache POI提供API给Java程序对Microsoft Office格式档案读和写的功能。POI为“Poor Obfuscation Implementation”的首字母缩写,意为“简洁版的模糊实现”。用它可以使用Java读取和创建,修改MS Excel文件。而且还可以使用Java读取和创建MS Word和MS PowerPoint文件等,本文主要介绍MS Excel的相关操作。

引入Apache POI组件

在Java开发中,我们一般从Spring Boot开始,所以本文主要以Spring Boot3框架下介绍Apache POI的使用,首先,我们需要在Spring Boot中引入Apache POI组件,引入方式如下:

打开pom.xml,在<dependencies>中添加如下依赖,如果大家需想要获取ApachePOI的最新版本,可以从Maven仓中去搜寻。

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

使用Apache POI组件操作Excel

MS Excel分老版(2007以前版本)和新版,老版是.xls后缀,新版是.xlsx后缀,同样在处理不同版本的Excel的时候,Apache POI也提供了两个不同的模块,分别是HSSF和XSSF:

HSSF:Horrible SpreadSheet Format,用于处理老版本的Excel文件,即“.xls”格式:

XSSF:XML SpreadSheet Format,用于处理新版本的Excel文件,即“.xlsx”格式。

本文主要介绍XSSF模块的使用。

1、新建工作簿

Workbook wb = new XSSFWorkbook();

try (OutputStream fileOut = new FileOutputStream("workbook.xlsx")) {
    wb.write(fileOut);
}

2、创建单元格

Workbook wb = new XSSFWorkbook();
CreationHelper createHelper = wb.getCreationHelper();
Sheet sheet = wb.createSheet("new sheet");

// Create a row and put some cells in it. Rows are 0 based.
Row row = sheet.createRow(0);

// Create a cell and put a value in it.
Cell cell = row.createCell(0);
cell.setCellValue(1);

// Or do it on one line.
row.createCell(1).setCellValue(1.2);
row.createCell(2).setCellValue(
     createHelper.createRichTextString("This is a string"));
row.createCell(3).setCellValue(true);

// Write the output to a file
try (OutputStream fileOut = new FileOutputStream("workbook.xls")) {
    wb.write(fileOut);
}

3、创建日期单元格

Workbook wb = new XSSFWorkbook();
CreationHelper createHelper = wb.getCreationHelper();

Sheet sheet = wb.createSheet("new sheet");

// Create a row and put some cells in it. Rows are 0 based.
Row row = sheet.createRow(0);

// Create a cell and put a date value in it.  The first cell is not styled
// as a date.
Cell cell = row.createCell(0);
cell.setCellValue(new Date());

// we style the second cell as a date (and time).  It is important to
// create a new cell style from the workbook otherwise you can end up
// modifying the built in style and effecting not only this cell but other cells.

CellStyle cellStyle = wb.createCellStyle();

cellStyle.setDataFormat(
    createHelper.createDataFormat().getFormat("m/d/yy h:mm"));

cell = row.createCell(1);
cell.setCellValue(new Date());
cell.setCellStyle(cellStyle);

//you can also set date as java.util.Calendar
cell = row.createCell(2);
cell.setCellValue(Calendar.getInstance());
cell.setCellStyle(cellStyle);

// Write the output to a file
try (OutputStream fileOut = new FileOutputStream("workbook.xls")) {
    wb.write(fileOut);
}

4、使用不同类型的单元格

Workbook wb = new XSSFWorkbook();

Sheet sheet = wb.createSheet("new sheet");

Row row = sheet.createRow(2);
row.createCell(0).setCellValue(1.1);
row.createCell(1).setCellValue(new Date());
row.createCell(2).setCellValue(Calendar.getInstance());
row.createCell(3).setCellValue("a string");
row.createCell(4).setCellValue(true);
row.createCell(5).setCellType(CellType.ERROR);

// Write the output to a file
try (OutputStream fileOut = new FileOutputStream("workbook.xls")) {
    wb.write(fileOut);
}

5、打开工作簿

工作簿可以从 File 或 InputStream 加载。使用 File 对象允许 更低的内存消耗,而 InputStream 需要更多的内存消耗 memory 的 SET 文件,因为它必须缓冲整个文件。

如果使用 WorkbookFactory,操作比较简单:

// Use a file
Workbook wb = WorkbookFactory.create(new File("MyExcel.xls"));

// Use an InputStream, needs more memory
Workbook wb = WorkbookFactory.create(new FileInputStream("MyExcel.xlsx"));

如果直接使用 HSSFWorkbook 或 XSSFWorkbook, 您通常应该通过 POIFSFileSystem 或 OPCPackage 来完全控制生命周期(包括 完成后关闭文件):

// XSSFWorkbook, File
OPCPackage pkg = OPCPackage.open(new File("file.xlsx"));
XSSFWorkbook wb = new XSSFWorkbook(pkg);

// TODO ....

pkg.close();

// XSSFWorkbook, InputStream, needs more memory
OPCPackage pkg = OPCPackage.open(myInputStream);
XSSFWorkbook wb = new XSSFWorkbook(pkg);

// TODO ....

pkg.close();

6、各种对齐选项

public static void main(String[] args) throws Exception {
    Workbook wb = new XSSFWorkbook(); 

    Sheet sheet = wb.createSheet();

    Row row = sheet.createRow(2);
    row.setHeightInPoints(30);

    createCell(wb, row, 0, HorizontalAlignment.CENTER, VerticalAlignment.BOTTOM);
    createCell(wb, row, 1, HorizontalAlignment.CENTER_SELECTION, VerticalAlignment.BOTTOM);
    createCell(wb, row, 2, HorizontalAlignment.FILL, VerticalAlignment.CENTER);
    createCell(wb, row, 3, HorizontalAlignment.GENERAL, VerticalAlignment.CENTER);
    createCell(wb, row, 4, HorizontalAlignment.JUSTIFY, VerticalAlignment.JUSTIFY);
    createCell(wb, row, 5, HorizontalAlignment.LEFT, VerticalAlignment.TOP);
    createCell(wb, row, 6, HorizontalAlignment.RIGHT, VerticalAlignment.TOP);

    // Write the output to a file
    try (OutputStream fileOut = new FileOutputStream("xssf-align.xlsx")) {
        wb.write(fileOut);
    }
    wb.close();
}

/**
 * Creates a cell and aligns it a certain way.
 *
 * @param wb     the workbook
 * @param row    the row to create the cell in
 * @param column the column number to create the cell in
 * @param halign the horizontal alignment for the cell.
 * @param valign the vertical alignment for the cell.
 */
private static void createCell(Workbook wb, Row row, int column, HorizontalAlignment halign, VerticalAlignment valign) {
    Cell cell = row.createCell(column);

    cell.setCellValue("Align It");

    CellStyle cellStyle = wb.createCellStyle();

    cellStyle.setAlignment(halign);
    cellStyle.setVerticalAlignment(valign);

    cell.setCellStyle(cellStyle);
}

7、使用边框

Workbook wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet("new sheet");

// Create a row and put some cells in it. Rows are 0 based.
Row row = sheet.createRow(1);

// Create a cell and put a value in it.
Cell cell = row.createCell(1);
cell.setCellValue(4);

// Style the cell with borders all around.
CellStyle style = wb.createCellStyle();
style.setBorderBottom(BorderStyle.THIN);
style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
style.setBorderLeft(BorderStyle.THIN);
style.setLeftBorderColor(IndexedColors.GREEN.getIndex());
style.setBorderRight(BorderStyle.THIN);
style.setRightBorderColor(IndexedColors.BLUE.getIndex());
style.setBorderTop(BorderStyle.MEDIUM_DASHED);
style.setTopBorderColor(IndexedColors.BLACK.getIndex());
cell.setCellStyle(style);

// Write the output to a file
try (OutputStream fileOut = new FileOutputStream("workbook.xls")) {
    wb.write(fileOut);
}
wb.close();

8、获取单元格内容

要获取单元格的内容,您首先需要 知道它是什么类型的 Cell (询问 String Cell ,因为它的数字内容将为您提供一个 NumberFormatException 的示例)。所以,你会 想要打开单元格的类型,然后调用 该单元格的适当 getter。

在下面的代码中,我们遍历每个单元格 在一张工作表中,打印出单元格的引用 (例如 A3),然后是单元格的内容。

// import org.apache.poi.ss.usermodel.*;
DataFormatter formatter = new DataFormatter();

Sheet sheet1 = wb.getSheetAt(0);

for (Row row : sheet1) {
    for (Cell cell : row) {
        CellReference cellRef = new CellReference(row.getRowNum(), cell.getColumnIndex());
        System.out.print(cellRef.formatAsString());

        System.out.print(" - ");

        // get the text that appears in the cell by getting the cell value and applying any data formats (Date, 0.00, 1.23e9, $1.23, etc)
        String text = formatter.formatCellValue(cell);

        System.out.println(text);

        // Alternatively, get the value and format it yourself
        switch (cell.getCellType()) {
            case CellType.STRING:
                System.out.println(cell.getRichStringCellValue().getString());
                break;
            case CellType.NUMERIC:
                if (DateUtil.isCellDateFormatted(cell)) {
                    System.out.println(cell.getDateCellValue());
                } else {
                    System.out.println(cell.getNumericCellValue());
                }
                break;
            case CellType.BOOLEAN:
                System.out.println(cell.getBooleanCellValue());
                break;
            case CellType.FORMULA:
                System.out.println(cell.getCellFormula());
                break;
            case CellType.BLANK:
                System.out.println();
                break;
            default:
                System.out.println();
        }
    }
}

9、文本提取

try (InputStream inp = new FileInputStream("workbook.xls")) {
    HSSFWorkbook wb = new XSSFWorkbook(new POIFSFileSystem(inp));
    ExcelExtractor extractor = new ExcelExtractor(wb);
    extractor.setFormulasNotResults(true);
    extractor.setIncludeSheetNames(false);
    String text = extractor.getText();
    wb.close();
}

10、填充和颜色

Workbook wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet("new sheet");

// Create a row and put some cells in it. Rows are 0 based.
Row row = sheet.createRow(1);

// Aqua background
CellStyle style = wb.createCellStyle();
style.setFillBackgroundColor(IndexedColors.AQUA.getIndex());
style.setFillPattern(FillPatternType.BIG_SPOTS);

Cell cell = row.createCell(1);
cell.setCellValue("X");
cell.setCellStyle(style);

// Orange "foreground", foreground being the fill foreground not the font color.
style = wb.createCellStyle();
style.setFillForegroundColor(IndexedColors.ORANGE.getIndex());
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);

cell = row.createCell(2);
cell.setCellValue("X");
cell.setCellStyle(style);

// Write the output to a file
try (OutputStream fileOut = new FileOutputStream("workbook.xls")) {
    wb.write(fileOut);
}
wb.close();
              

11、合并单元格

Workbook wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet("new sheet");

Row row = sheet.createRow(1);

Cell cell = row.createCell(1);
cell.setCellValue("This is a test of merging");

sheet.addMergedRegion(new CellRangeAddress(
        1, //first row (0-based)
        1, //last row  (0-based)
        1, //first column (0-based)
        2  //last column  (0-based)
));

// Write the output to a file
try (OutputStream fileOut = new FileOutputStream("workbook.xls")) {
    wb.write(fileOut);
}
wb.close();

12、使用字体

Workbook wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet("new sheet");

// Create a row and put some cells in it. Rows are 0 based.
Row row = sheet.createRow(1);

// Create a new font and alter it.
Font font = wb.createFont();
font.setFontHeightInPoints((short)24);
font.setFontName("Courier New");
font.setItalic(true);
font.setStrikeout(true);

// Fonts are set into a style so create a new one to use.
CellStyle style = wb.createCellStyle();
style.setFont(font);

// Create a cell and put a value in it.
Cell cell = row.createCell(1);
cell.setCellValue("This is a test of fonts");
cell.setCellStyle(style);

// Write the output to a file
try (OutputStream fileOut = new FileOutputStream("workbook.xls")) {
    wb.write(fileOut);
}
wb.close();

13、自定义颜色

XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = wb.createSheet();

XSSFRow row = sheet.createRow(0);

XSSFCell cell = row.createCell( 0);
cell.setCellValue("custom XSSF colors");

XSSFCellStyle style1 = wb.createCellStyle();
style1.setFillForegroundColor(new XSSFColor(new java.awt.Color(128, 0, 128), new DefaultIndexedColorMap()));

style1.setFillPattern(FillPatternType.SOLID_FOREGROUND);

标签:Java,wb,Excel,cell,createCell,POI,new,sheet,row
From: https://blog.csdn.net/jackiendsc/article/details/144104068

相关文章

  • Javascript遍历目录时使用for..in循环无法获取Files对象和SubFolders对象问题的解决方
      1Javascript遍历目录时使用for..in循环无法获取Files对象和SubFolders对象1.1问题场景  在JavaScript中遍历目录,使用for..in循环时,无法获取到Files对象和SubFolders对象,导致无法遍历目录和子目录。  代码如下:functionGetAllFilesInSubFolder(path,filter)......
  • 【Java毕业设计】基于Springcloud+SpringBoot+Vue的智慧养老系统
    源码获取:https://download.csdn.net/download/u011832806/89426620基于Springcloud+SpringBoot+Vue的智慧养老系统开发语言:Java数据库:MySQL技术:Springcloud+SpringBoot+MyBatis+Vue.js+Eureka+elementUI工具:IDEA/Ecilpse、Navicat、Maven系统演示视频:链接:https://pan.b......
  • idea报错:java:无效的源发行版:12
    问题描述:Error:java:无效的源发行版:12使用idea运行项目的时候,报出错误:Error:java:无效的源发行版:XXX。这是因为idea设置的jdk版本和运行的项目版本的jdk版本号没有统一!!!解决办法:比如我要用的是1.8版本,全部统一成1.8。1.首先点击File->ProjectStructure2.查看Project中的Proj......
  • java--类
    文章目录前言在掌握C语言基本语法后,我们过渡到java语言,看看java相对于C有哪些区别。本文源代码网址:https://gitee.com/zfranklin/java/tree/master/Arr/src/com/njupt/base面向对象类(Class)类的成员变量命名方式public/private前言在掌握C语言基本语法后,我们过渡......
  • 三分钟理解Java中向上转型和向下转型
    场景:在学习Java的过程中,理解向上转型(Upcasting)和向下转型(Downcasting)对于掌握面向对象编程中的多态性至关重要。本文将通过简单的例子来阐述这两个概念的作用和意义。什么是向上转型和向下转型对象向上转型父类对象可以调用子类重写父类的方法,这样当需要新添功能时,只需要......
  • 判断一个自然数是否为完全数(Java)
    importjava.util.Scanner;publicclass完全数{publicstaticvoidmain(String[]args){//输入一个自然数,判断是不是完全数//完全数:所有因子之和等于该数本身Scannersc=newScanner(System.in);System.out.println("请输......
  • Java小白学习之---接口
    1.什么是接口?接口就是给出一些没有实现的方法,封装到一起,到某个类要使用的时候,在根据具体情况把这些方法写出来2.接口语法interface接口名{//属性//方法(1.抽象方法2默认实现方法3.静态方法)}class类名implements接口{自己属性;自己方法;必须实现的接口的抽象......
  • C# + html + fetch + API + javascript
    本随笔,在html利用fetch去callwebapi对数据进行添加,修改,更新和删除。数据库与存储过程,此处略过...创建entity,方便webapi进行互动。 现在可以写WebAPI,html实现添加数据, jsfile, 上面添加的数据,将以下面的数据列呈现,  Insus.NET只是在html静态写了数据的表......
  • Java的现代应用与未来趋势:全面解析2024年技术生态
    引言:Java的演进与现代化技术方向Java的历史与演变​Java自1995年由SunMicrosystems发布以来,已经发展成世界上最流行的编程语言之一。它的设计目标是“WriteOnce,RunAnywhere”(写一次,随处运行),依靠其平台无关性(JVM)得到了广泛应用。随着技术的不断演变,Java语言的版本也......
  • Java设计模式——适配器模式的精妙应用:探秘 JDK 源码中的 Set 类
    在Java编程的世界里,JDK源码犹如一座神秘的宝藏,其中的Set类更是我们日常开发中频繁使用的利器。今天,就让我们像勇敢的探险家一样,深入JDK源码,揭开Set类的神秘面纱,重点剖析适配器模式在其中的巧妙应用,看看它是如何让Set类焕发出独特魅力的!......