帮我用java生成一个excel表
时间: 2023-03-21 12:02:24 浏览: 123
好的,以下是使用Java生成Excel表格的示例代码:
首先需要引入Apache POI库,可以在pom.xml文件中添加以下依赖:
```xml
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
```
接下来就可以开始编写生成Excel表格的代码了:
```java
import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.ss.usermodel.Sheet;
public class ExcelGenerator {
public static void main(String[] args) {
try {
// 创建Excel工作簿
XSSFWorkbook workbook = new XSSFWorkbook();
// 创建Excel表格
Sheet sheet = workbook.createSheet("My Sheet");
// 创建表头
Row headerRow = sheet.createRow(0);
Cell headerCell1 = headerRow.createCell(0);
headerCell1.setCellValue("姓名");
Cell headerCell2 = headerRow.createCell(1);
headerCell2.setCellValue("年龄");
// 填充数据
Row dataRow1 = sheet.createRow(1);
Cell dataCell1 = dataRow1.createCell(0);
dataCell1.setCellValue("张三");
Cell dataCell2 = dataRow1.createCell(1);
dataCell2.setCellValue(20);
Row dataRow2 = sheet.createRow(2);
Cell dataCell3 = dataRow2.createCell(0);
dataCell3.setCellValue("李四");
Cell dataCell4 = dataRow2.createCell(1);
dataCell4.setCellValue(25);
// 将Excel工作簿写入文件
FileOutputStream fileOut = new FileOutputStream("example.xlsx");
workbook.write(fileOut);
fileOut.close();
// 提示文件生成成功
System.out.println("Excel文件生成成功!");
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
上述代码会生成一个名为“example.xlsx”的Excel文件,并在其中创建一个名为“My Sheet”的工作表,包含姓名和年龄两列数据,生成结果如下所示:
| 姓名 | 年龄 |
| :----: | :----: |
| 张三 | 20 |
| 李四 | 25 |
你可以根据需要修改代码中的表头、数据等内容以生成自己需要的Excel表格。