java 实现数据导出功能
时间: 2023-11-28 17:05:27 浏览: 38
Java实现数据导出功能可以使用Apache POI库或者JExcel API库来实现。这两个库都可以实现Excel格式文件的导出。
下面是一个使用Apache POI库实现Excel导出的示例代码:
```java
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelExporter {
public static void exportExcel(String[] headers, Object[][] data, String filePath) throws IOException {
Workbook workbook = null;
if (filePath.endsWith(".xls")) {
workbook = new HSSFWorkbook();
} else if (filePath.endsWith(".xlsx")) {
workbook = new XSSFWorkbook();
} else {
throw new IllegalArgumentException("Invalid file extension: " + filePath);
}
Sheet sheet = workbook.createSheet();
// create header row
Row headerRow = sheet.createRow(0);
for (int i = 0; i < headers.length; i++) {
Cell cell = headerRow.createCell(i);
cell.setCellValue(headers[i]);
}
// create data rows
for (int i = 0; i < data.length; i++) {
Row dataRow = sheet.createRow(i + 1);
for (int j = 0; j < data[i].length; j++) {
Cell cell = dataRow.createCell(j);
cell.setCellValue(data[i][j].toString());
}
}
// write workbook to file
try (FileOutputStream outputStream = new FileOutputStream(filePath)) {
workbook.write(outputStream);
}
}
}
```
使用示例:
```java
public static void main(String[] args) {
String[] headers = {"Name", "Age", "Gender"};
Object[][] data = {
{"Alice", 23, "Female"},
{"Bob", 30, "Male"},
{"Charlie", 45, "Male"}
};
String filePath = "data.xlsx";
try {
ExcelExporter.exportExcel(headers, data, filePath);
System.out.println("Data exported successfully to file: " + filePath);
} catch (IOException e) {
System.err.println("Error exporting data: " + e.getMessage());
}
}
```
以上代码将数据导出到 `data.xlsx` 文件中。你可以根据需要修改代码以适应你的具体情况。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)