Excel学习1_Java读取文件中的内容写入excel中

来源:互联网 发布:日本人彻底疯了 知乎 编辑:程序博客网 时间:2024/06/05 06:30

public static void writeXls() {//把读取的文件写入到excel文件中
  int i = 0;
  try {
   File file = new File("d:/cn.csv");
   if (file.isFile() && file.exists()) {
    InputStreamReader read = new InputStreamReader(
      new FileInputStream(file));
    BufferedReader bufferReader = new BufferedReader(read);
    String lineTxt = null;
    String[] arg = null;
    getConnection();
    List<String[]> list = new ArrayList<String[]>() ;
    lineTxt = bufferReader.readLine();
    try {
     String tempDate;
     while (lineTxt != null && !lineTxt.trim().equals("")) {
      i++;
      arg = lineTxt.split(",");
      list.add(arg) ;
      lineTxt = bufferReader.readLine();
     }
     for(String[] args:list){
      System.out.println(args[0]+" "+args[1]+" "+args[2]+" "+args[3]);
     }
     
     operateExl(list) ;
    } catch (Exception e) {
     e.printStackTrace();
    }
   } else {
    System.out.println("文件路径不正确!");
   }
  } catch (Exception e) {
   System.out.println("文件错误!");
  } finally {
   System.out.println(i);
  }
 }
 public static void operateExl(List<String[]> list) {
  try {
   WritableWorkbook wb = Workbook.createWorkbook(new File("d:/test.xls")) ;
   WritableSheet sheet = wb.createSheet("第一页", 0) ;
   for(int i=0;i<list.size();i++){
    String arg[] = list.get(i) ;
    for(int j=0;j<arg.length;j++){
     sheet.addCell(new Label(j,i,arg[j])) ;
    }
   }
   wb.write() ;
   wb.close() ;
   } catch (Exception e) {
   // TODO: handle exception
   e.printStackTrace() ;
  }
 }

 public static void main(String[] args) {
  writeXls();
 }

原文来自:https://yq.aliyun.com/articles/48968

原创粉丝点击