java的excel导出hashmap数据
时间: 2023-12-10 16:34:36 浏览: 84
java 将数据导出到Excel中
5星 · 资源好评率100%
以下是Java中使用EasyExcel库导出HashMap数据到Excel的示例代码:
```java
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ExcelExportUtil {
public static void exportExcel(List<Map<String, Object>> dataList, String fileName, String sheetName) throws IOException {
// 构造ExcelWriter对象
ExcelWriter excelWriter = EasyExcel.write(fileName).build();
// 构造WriteSheet对象
WriteSheet writeSheet = EasyExcel.writerSheet(sheetName).build();
// 构造表头
List<String> headList = new ArrayList<>();
for (String key : dataList.get(0).keySet()) {
headList.add(key);
}
// 写入表头
excelWriter.writeHead(headList, writeSheet);
// 写入数据
List<List<Object>> dataList2 = new ArrayList<>();
for (Map<String, Object> data : dataList) {
List<Object> rowList = new ArrayList<>();
for (String key : headList) {
rowList.add(data.get(key));
}
dataList2.add(rowList);
}
excelWriter.write(dataList2, writeSheet);
// 关闭ExcelWriter对象
excelWriter.finish();
}
public static void main(String[] args) throws IOException {
// 构造测试数据
List<Map<String, Object>> dataList = new ArrayList<>();
for (int i = 1; i <= 10; i++) {
Map<String, Object> data = new HashMap<>();
data.put("id", i);
data.put("name", "name" + i);
data.put("age", 20 + i);
dataList.add(data);
}
// 导出Excel
exportExcel(dataList, "test.xlsx", "Sheet1");
}
}
```
以上代码中,我们使用EasyExcel库来实现Excel的导出。首先,我们构造ExcelWriter对象和WriteSheet对象,然后构造表头,写入表头,最后写入数据即可。需要注意的是,EasyExcel库要求数据必须是List<List<Object>>类型,因此我们需要将HashMap数据转换为这种类型。另外,如果HashMap中有Date类型的字段,需要将其转换为String类型,否则会报错。
阅读全文