![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 package test; 2 3 import java.io.BufferedReader; 4 import java.io.File; 5 import java.io.FileInputStream; 6 import java.io.IOException; 7 import java.io.InputStreamReader; 8 import java.util.ArrayList; 9 import java.util.List; 10 11 import jxl.Workbook; 12 import jxl.write.Label; 13 import jxl.write.WritableSheet; 14 import jxl.write.WritableWorkbook; 15 import jxl.write.WriteException; 16 import jxl.write.biff.RowsExceededException; 17 18 public class ConvertTxtExcel { 19 private static List<Account> list = new ArrayList<Account>(); 20 private final static String TXTFILENAME = "F:\\\\myTxt.txt"; 21 private final static String EXCELFILENAME = "F:\\\\myExcel.xls"; 22 23 public static void main(String[] args) { 24 getTxt(); 25 txtToExcel(); 26 } 27 28 private static void txtToExcel() { 29 WritableWorkbook wwk = null; 30 try { 31 wwk = Workbook.createWorkbook(new File(EXCELFILENAME)); 32 WritableSheet ws = wwk.createSheet("Test1", 0); 33 Label label1 = new Label(0, 0, "id"); 34 Label label2 = new Label(1, 0, "user"); 35 Label label3 = new Label(2, 0, "paw"); 36 Label label4 = new Label(3, 0, "age"); 37 // 将定义好的单元格添加到工作表中 38 ws.addCell(label1); 39 ws.addCell(label2); 40 ws.addCell(label3); 41 ws.addCell(label4); 42 /* 43 * 生成一个保存数字的单元格 必须使用Number的完整包路径,否则有语法歧义 44 */ 45 for (int i = 0; i < list.size(); i++) { 46 Account p = list.get(i); 47 jxl.write.Number id = new jxl.write.Number(0, (i + 1), p.getId()); 48 Label label5 = new Label(1, (i + 1), p.getUser()); 49 Label label6 = new Label(2, (i + 1), p.getPaw()); 50 jxl.write.Number age = new jxl.write.Number(3, (i + 1), p.getAge()); 51 ws.addCell(id); 52 ws.addCell(label5); 53 ws.addCell(label6); 54 ws.addCell(age); 55 } 56 wwk.write(); 57 wwk.close(); 58 } catch (IOException e) { 59 e.printStackTrace(); 60 } catch (RowsExceededException e) { 61 e.printStackTrace(); 62 } catch (WriteException e) { 63 e.printStackTrace(); 64 } 65 System.out.println("完成"); 66 } 67 68 private static List<Account> getTxt() { 69 try { 70 BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(TXTFILENAME), "utf-8")); 71 String line = ""; 72 while ((line = br.readLine()) != null) { 73 //TXT里面的数据都是用-隔开的,例如:1-haha-123123-12 74 String[] arr = line.split("-"); 75 Account account = new Account(Integer.parseInt(arr[0]), arr[1], arr[2], Integer.parseInt(arr[3])); 76 list.add(account); 77 } 78 } catch (NumberFormatException e) { 79 e.printStackTrace(); 80 } catch (IOException e) { 81 e.printStackTrace(); 82 } 83 return list; 84 } 85 }
结果:
注意事项:需要导 jxl.jar