Java中写成xlsx文件
时间: 2024-03-11 09:48:23 浏览: 23
可以使用Apache POI库来在Java中写入.xlsx文件。以下是一个简单的例子:
```java
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
public class WriteExcelFile {
public static void main(String[] args) throws IOException {
// Create a new .xlsx file
XSSFWorkbook workbook = new XSSFWorkbook();
// Create a blank sheet
XSSFSheet sheet = workbook.createSheet("Sheet1");
// Create a header row
Row headerRow = sheet.createRow(0);
headerRow.createCell(0).setCellValue("Name");
headerRow.createCell(1).setCellValue("Age");
headerRow.createCell(2).setCellValue("City");
// Add data rows
Row dataRow1 = sheet.createRow(1);
dataRow1.createCell(0).setCellValue("John");
dataRow1.createCell(1).setCellValue(25);
dataRow1.createCell(2).setCellValue("New York");
Row dataRow2 = sheet.createRow(2);
dataRow2.createCell(0).setCellValue("Jane");
dataRow2.createCell(1).setCellValue(30);
dataRow2.createCell(2).setCellValue("Los Angeles");
// Write the workbook to a file
FileOutputStream fileOut = new FileOutputStream(new File("example.xlsx"));
workbook.write(fileOut);
fileOut.close();
// Close the workbook
workbook.close();
}
}
```
这个例子创建了一个名为"example.xlsx"的新文件,并向其中写入一些数据。它使用了XSSFWorkbook和XSSFSheet类来创建工作簿和工作表,使用Row和Cell类来创建行和单元格。最后,它使用FileOutputStream将工作簿写入磁盘并关闭它。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)