云
2 天以前 657698fd2fb32794932474648dbaee9e284e38c8
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import java.nio.file.*;
import java.io.*;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
class ExtractBomXls {
 static String q(String s){return "\""+s.replace("\\","\\\\").replace("\"","\\\"").replace("\r","\\r").replace("\n","\\n").replace("\t","\\t")+"\"";}
 public static void main(String[] args)throws Exception{
  StringBuilder out=new StringBuilder("[");
  try(var w=new HSSFWorkbook(Files.newInputStream(Path.of(args[0])))){
   for(int si=0;si<w.getNumberOfSheets();si++){
    var s=w.getSheetAt(si);if(si>0)out.append(',');out.append("{\"sheet\":").append(q(s.getSheetName())).append(",\"rows\":[");
    for(int ri=0;ri<=s.getLastRowNum();ri++){
     if(ri>0)out.append(',');out.append('[');var r=s.getRow(ri);
     if(r!=null)for(int ci=0;ci<r.getLastCellNum();ci++){
      if(ci>0)out.append(',');var c=r.getCell(ci);if(c==null){out.append("null");continue;}
      var t=c.getCellType()==CellType.FORMULA?c.getCachedFormulaResultType():c.getCellType();
      if(t==CellType.NUMERIC)out.append(java.math.BigDecimal.valueOf(c.getNumericCellValue()).stripTrailingZeros().toPlainString());
      else if(t==CellType.STRING)out.append(q(c.getStringCellValue()));else if(t==CellType.BLANK)out.append("null");else throw new Exception("Unexpected cell "+s.getSheetName()+":"+c.getAddress());
     }out.append(']');
    }out.append("]}");
   }
  }out.append(']');Files.writeString(Path.of(args[1]),out.toString());
 }
}