一、背景
有一个excel文件(.xlsx),内容是这样的。
现在需要将它解析成{"小兰":20,"小黄":10}这样的json格式写入到一个txt文本文件中。
二、步骤
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.FileInputStream;
import java.io.FileOutputStream;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.io.IOUtils;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import com.alibaba.fastjson.JSON;
public class Test {
public static void main(String[] args) throws Exception {
Map<String, Long> map = new HashMap<>();
XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream("1.xlsx"));
XSSFSheet sheet = workbook.getSheetAt(0);
for (int i = 0; i < sheet.getLastRowNum() + 1; i++) {
XSSFRow row = sheet.getRow(i);
if (row != null) {
Object o1 = getValue(row.getCell(0));
Object o2 = getValue(row.getCell(1));
if (o1 != null) {
String s1 = o1.toString().trim();
Long num1 = Long.parseLong(o2.toString().trim());
map.put(s1, num1);
}
}
}
IOUtils.write(JSON.toJSONString(map), new FileOutputStream("1.txt"), Charset
.defaultCharset());
}
public static Object getValue(XSSFCell cell) {
if (cell == null) {
return null;
}
if (cell.getCellType() == CellType.STRING) {
return cell.getStringCellValue();
}
if (cell.getCellType() == CellType.NUMERIC) {
return (long)cell.getNumericCellValue();
}
return null;
}
}