21xrx.com
2025-03-25 07:23:07 Tuesday
文章检索 我的文章 写文章
如何使用Java程序导出Excel表格?
2023-06-11 11:42:17 深夜i     --     --
Java 导出 Excel

在日常工作中,常常需要将数据导出到Excel表格中。本文将介绍使用Java程序将数据导出到Excel表格中的方法。首先,我们需要引入poi-ooxml包,该包是Apache POI项目中的一个子项目,可用于操作Excel、Word和PowerPoint等Microsoft Office格式文件。

以下是一个简单的示例代码:

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileOutputStream;
import java.io.IOException;
public class ExcelExporter {
  public void exportToExcel() {
    // 创建Workbook对象,表示整个Excel文档
    Workbook workbook = new XSSFWorkbook();
    // 创建Sheet对象,表示一个工作表
    Sheet sheet = workbook.createSheet("Sheet1");
    // 创建Row对象,表示一行
    Row row = sheet.createRow(0);
    // 创建单元格并设置值
    Cell cell1 = row.createCell(0);
    cell1.setCellValue("姓名");
    Cell cell2 = row.createCell(1);
    cell2.setCellValue("年龄");
    // 创建数据行并填充数据
    for (int i = 1; i < 4; i++) {
      Row dataRow = sheet.createRow(i);
      Cell dataCell1 = dataRow.createCell(0);
      dataCell1.setCellValue("小明");
      Cell dataCell2 = dataRow.createCell(1);
      dataCell2.setCellValue(i*10);
    }
    // 导出Excel文件
    try {
      FileOutputStream outputStream = new FileOutputStream("test.xlsx");
      workbook.write(outputStream);
      outputStream.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
  public static void main(String[] args) {
    ExcelExporter exporter = new ExcelExporter();
    exporter.exportToExcel();
  }
}

运行该程序后,会生成一个名为test.xlsx的Excel文件,内容如下:

| 姓名 | 年龄 |

| --- | --- |

| 小明 | 10 |

| 小明 | 20 |

| 小明 | 30 |

使用Java程序导出Excel表格可以很方便地将数据从数据库或其他数据源中导出到Excel表格中,方便进行数据分析和处理。

  
  

评论区