Java 通过json数据导出excel表,并返回下载url
时间: 2023-05-28 16:05:11 浏览: 195
以下是Java代码示例,通过json数据导出excel表,并返回下载url:
```java
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
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.ss.usermodel.Workbook;
import com.alibaba.fastjson.JSON;
public class ExcelExportUtil {
public static String exportToExcel(String jsonData) throws IOException {
// 解析json数据
List<Map<String, Object>> dataList = JSON.parseObject(jsonData, List.class);
// 创建excel工作簿
Workbook workbook = new HSSFWorkbook();
// 创建第一个sheet页
Sheet sheet = workbook.createSheet("Sheet1");
// 创建表头
Row headerRow = sheet.createRow(0);
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++);
cellIndex = 0;
for (Object value : data.values()) {
Cell cell = row.createCell(cellIndex++);
if (value instanceof Number) {
cell.setCellValue(((Number) value).doubleValue());
} else {
cell.setCellValue(value.toString());
}
}
}
// 生成文件名
String fileName = UUID.randomUUID().toString() + ".xls";
// 保存excel文件
File file = new File(fileName);
OutputStream os = new FileOutputStream(file);
workbook.write(os);
os.close();
// 返回下载url
String url = file.toURI().toURL().toString();
return url;
}
public static void main(String[] args) throws IOException {
// 测试数据
List<Map<String, Object>> dataList = new ArrayList<Map<String, Object>>();
Map<String, Object> data1 = new LinkedHashMap<String, Object>();
data1.put("name", "张三");
data1.put("age", 20);
data1.put("gender", "男");
dataList.add(data1);
Map<String, Object> data2 = new LinkedHashMap<String, Object>();
data2.put("name", "李四");
data2.put("age", 25);
data2.put("gender", "女");
dataList.add(data2);
// 导出excel并返回下载url
String url = exportToExcel(JSON.toJSONString(dataList));
System.out.println(url);
}
}
```
阅读全文