java导出excel表
时间: 2023-10-14 09:06:04 浏览: 50
要使用Java导出Excel表,您需要使用Apache POI库。以下是一个示例代码,该代码将数据从Java中的ArrayList导出到Excel表中。
```java
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelExporter {
public static void export(List<String> data, String fileName) throws IOException {
XSSFWorkbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("Sheet1");
int rowCount = 0;
for (String item : data) {
Row row = sheet.createRow(rowCount++);
Cell cell = row.createCell(0);
cell.setCellValue(item);
}
FileOutputStream outputStream = new FileOutputStream(fileName);
workbook.write(outputStream);
workbook.close();
outputStream.close();
}
public static void main(String[] args) throws IOException {
List<String> data = new ArrayList<>();
data.add("Item 1");
data.add("Item 2");
data.add("Item 3");
export(data, "data.xlsx");
}
}
```
在此示例中,我们创建一个名为“Sheet1”的工作表,并将数据添加到单元格中。然后,我们将表格保存到指定的文件中。请注意,此代码使用XSSFWorkbook类来创建Excel工作簿。如果您需要创建旧版本的Excel文件(.xls),则应使用HSSFWorkbook类。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)