java POI 将txt文件导入到excel中

来源:互联网 发布:双筒望远镜 知乎 编辑:程序博客网 时间:2024/05/18 01:33

简单demo

数据结构:包含三个string类型的数据,且都被逗号分隔开,导入到excel中

ValueObject .java 类

package XlsDto2Excel;public class ValueObject {private String name;      /**名称**/private String value;    /**值**/private String unit;    /**单位**/private boolean isComment = false;private String comment;public ValueObject(String name,String value, String unit) {this.value = value;this.unit = unit;    this.name = name;}public ValueObject(String comment) {this.comment = comment;this.isComment = true;}public boolean isComment() {return isComment;}public String getComment() {return comment != null ? comment : "";}public String getName() {return name != null ? name : "";}public String getValue() {return value != null ? value : "";}public String getUnit() {return unit != null ? unit : "";}}
allmain.java

package XlsDto2Excel;import org.apache.poi.hssf.usermodel.HSSFRow;import org.apache.poi.hssf.usermodel.HSSFSheet;import org.apache.poi.hssf.usermodel.HSSFWorkbook;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.util.*;public class allmain {public static void main(String[] args) throws IOException {Scanner in = null;        List<String> inStrs = new ArrayList<>();        try {            in = new Scanner(new File("E:/data_stats_0.txt"));            while (in.hasNextLine()) {                inStrs.add(in.nextLine());            }        } catch (Exception e) {            e.printStackTrace();        } finally {            if (in != null) {                in.close();            }        }        List<ValueObject> vals = new ArrayList<>();        for (String str : inStrs) {            str = str.trim();            if (str.startsWith("**") && str.endsWith("**")) {                vals.add(new ValueObject(str));            } else {                String[] res = str.split(",", 3);                if (res.length == 3) {                    vals.add(new ValueObject(res[0], res[1], res[2]));                }            }        }        HSSFWorkbook workbook = new HSSFWorkbook();        HSSFSheet sheet = workbook.createSheet("default");        for (int i = 0; i < vals.size(); ++i) {            HSSFRow row = sheet.createRow(i);            ValueObject val = vals.get(i);            if (val.isComment()) {                row.createCell(7).setCellValue(val.getComment());            } else {                row.createCell(7).setCellValue(val.getName());                row.createCell(8).setCellValue(val.getValue());                row.createCell(9).setCellValue(val.getUnit());            }        }        try {            FileOutputStream out = new FileOutputStream(new File("E:/data_stats_0.xls"));            workbook.write(out);            out.close();        } catch (Exception e) {            e.printStackTrace();        }        workbook.close();}}


0 0