gpt-4-1106-preview· OpenAI
WildChat-4.8M (AI2)
java 根据前端传来的数据导出成为excel
- User
java 根据前端传来的数据导出成为excel
- Assistant
java 根据前端传来的数据导出成为excel
在Java中,可以使用Apache POI库来根据前端传来的数据导出成为Excel。Apache POI是一个很流行的用于处理Microsoft Office文档的开源库,勇于读写Excel、Word等格式的文件。
以下是一个使用Apache POI导出数据为Excel格式的基本示例:
pom.xml文件里加入以下依赖:<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>5.2.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.2.2</version>
</dependency>
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.Map;
public class ExcelExporter {
public static void exportDataToExcel(List<Map<String, Object>> dataList, String filePath) {
// 创建工作簿
Workbook workbook = new XSSFWorkbook();
// 创建一个工作表(sheet)
Sheet sheet = workbook.createSheet("Data");
// 创建表头行
Row headerRow = sheet.createRow(0);
if (!dataList.isEmpty()) {
int cellIndex = 0;
for (String key : dataList.get(0).keySet()) {
Cell cell = headerRow.createCell(cellIndex++);
cell.setCellValue(key);
}
}
// 填充数据
int rowIndex = 1;
for (Map<String, Object> data : dataList) {
Row row = sheet.createRow(rowIndex++);
int cellIndex = 0;
for (Object value : data.values()) {
Cell cell = row.createCell(cellIndex++);
if (value instanceof String) {
cell.setCellValue((String) value);
} else if (value instanceof Integer) {
cell.setCellValue((Integer) value);
} else if (value instanceof Double) {
cell.setCellValue((Double) value);
}
// 可以添加更多类型的判断
}
}
// 写入数据到文件中
try (FileOutputStream fos = new FileOutputStream(filePath)) {
workbook.write(fos);
} catch (IOException e) {
e.printStackTrace();
}
// 关闭工作簿
try {
workbook.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
exportDataToExcel方法,传入从前端获取的数据(假设是一个包含有Map的List,每个Map表示一行数据),以及你想要保存的文件路径:List<Map<String, Object>> dataList = ... // 前端传来的数据
String filePath = "D:/example.xlsx"; // 你想要保存的位置和文件名
ExcelExporter.exportDataToExcel(dataList, filePath);
这样就可以根据前端传来的数据生成Excel文件了。记得处理好前端到后端数据的传输,比如可以通过HTTP请求体传输JSON数据给后端,然后后端解析JSON并使用上述方法导出为Excel。
Not yet included in a published release.