Java输出指定格式的excel表格
时间: 2024-06-09 21:10:00 浏览: 17
要输出指定格式的Excel表格,你可以使用Apache POI库。下面是一个简单的Java代码示例,它演示了如何使用POI API来创建和设置Excel表格的格式:
```java
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelWriter {
public static void main(String[] args) throws IOException {
// 创建工作簿
Workbook workbook = new XSSFWorkbook();
// 创建工作表
Sheet sheet = workbook.createSheet("Sheet1");
// 创建行
Row row = sheet.createRow(0);
// 创建单元格
Cell cell = row.createCell(0);
cell.setCellValue("姓名");
cell = row.createCell(1);
cell.setCellValue("年龄");
// 设置单元格格式
CellStyle style = workbook.createCellStyle();
style.setFillForegroundColor(IndexedColors.LIGHT_BLUE.getIndex());
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
cell.setCellStyle(style);
// 写入数据
row = sheet.createRow(1);
cell = row.createCell(0);
cell.setCellValue("张三");
cell = row.createCell(1);
cell.setCellValue(25);
// 输出文件
FileOutputStream fileOut = new FileOutputStream("output.xlsx");
workbook.write(fileOut);
fileOut.close();
// 关闭工作簿
workbook.close();
}
}
```
在该示例中,我们创建了一个工作簿、一个工作表、一行和两个单元格。然后我们设置了单元格的格式,并将数据写入单元格。最后,我们将工作簿输出到文件中。
注意:在使用该代码之前,你需要在你的项目中添加POI库的依赖项。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.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)