本段代碼的目的是從txt文本中讀取相應格式的數據,然后寫入到對應格式的excel文檔中
在敲本段代碼的時候,也學習了一些其它知識點,如下:
1、byte[] b_charset= String.getBytes("charset");就是返回字符串在給定的charset編碼格式下的表現,保存在byte[]數組里面。charset可以是utf-8,gbk,iso8859-1等
2、String s_charset = new String(b_charset,"charset");使用指定編碼格式把byte[]解析成String格式。charset可以是utf-8,gbk,iso8859-1等
3、System.exit(0)是正常退出程序,而System.exit(1)或者說非0表示非正常退出程序
第1第2條學習來源:String的getBytes()方法
第3條學習來源:System.exit(0)和System.exit(1)區別
讀取txt生成excel學習來源:Java生成和操作Excel文件
完整代碼如下:
package test; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import jxl.Workbook; import jxl.write.Label; import jxl.write.WritableSheet; import jxl.write.WritableWorkbook; import jxl.write.WriteException; import jxl.write.biff.RowsExceededException; public class txt2excel { public static void main(String[] args) { File file = new File("C:\\Users\\Desktop\\bbb.txt");// 將讀取的txt文件 File file2 = new File("C:\\Users\\Desktop\\work.xls");// 將生成的excel表格 if (file.exists() && file.isFile()) { InputStreamReader read = null; String line = ""; BufferedReader input = null; WritableWorkbook wbook = null; WritableSheet sheet; try { read = new InputStreamReader(new FileInputStream(file), "gbk"); input = new BufferedReader(read); wbook = Workbook.createWorkbook(file2);// 根據路徑生成excel文件 sheet = wbook.createSheet("first", 0);// 新標簽頁 try { Label company = new Label(0, 0, "公司名稱");// 如下皆為列名 sheet.addCell(company); Label position = new Label(1, 0, "崗位"); sheet.addCell(position); Label salary = new Label(2, 0, "薪資"); sheet.addCell(salary); Label status = new Label(3, 0, "狀態"); sheet.addCell(status); } catch (RowsExceededException e) { e.printStackTrace(); } catch (WriteException e) { e.printStackTrace(); } int m = 1;// excel行數 int n = 0;// excel列數 Label t; while ((line = input.readLine()) != null) { String[] words = line.split("[ \t]");// 把讀出來的這行根據空格或tab分割開 for (int i = 0; i < words.length; i++) { if (!words[i].matches("\\s*")) { // 當不是空行時 t = new Label(n, m, words[i].trim()); sheet.addCell(t); n++; } } n = 0;// 回到列頭部 m++;// 向下移動一行 } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (RowsExceededException e) { e.printStackTrace(); } catch (WriteException e) { e.printStackTrace(); } finally { try { wbook.write(); wbook.close(); input.close(); read.close(); } catch (IOException e) { e.printStackTrace(); } catch (WriteException e) { e.printStackTrace(); } } System.out.println("over!"); System.exit(0); } else { System.out.println("file is not exists or not a file"); System.exit(0); } } }