一、背景
现在需要将一个map里的数据写入到一个excel文件中。
二、步骤
1.创建springboot项目,引入依赖。
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>5.0.0</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.0.0</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.8.0</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.75</version>
</dependency>
2.代码
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
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.streaming.SXSSFWorkbook;
public class Test {
public static void main(String[] args) throws IOException {
Map<String, String> map = new HashMap<>();
map.put("lili", "男");
map.put("lsss", "女");
List<String> header = Arrays.asList("姓名", "性别");
SXSSFWorkbook workbook = new SXSSFWorkbook();
Sheet sheet = workbook.createSheet();
Row row = sheet.createRow(0);
for (int j = 0; j < header.size(); j++) {
Cell cell = row.createCell(j);
HSSFRichTextString text = new HSSFRichTextString(header.get(j));
cell.setCellValue(text);
}
int index = 1;
for (Entry<String, String> entry : map.entrySet()) {
Row row2 = sheet.createRow(index++);
Cell cell1 = row2.createCell(0);
HSSFRichTextString text1 = new HSSFRichTextString(entry.getKey());
cell1.setCellValue(text1);
Cell cell2 = row2.createCell(1);
HSSFRichTextString text2 = new HSSFRichTextString(entry.getValue());
cell2.setCellValue(text2);
}
workbook.write(new FileOutputStream("1.xlsx"));
}
}
3.生成的文件