1 import java.io.BufferedReader; 2 import java.io.File; 3 import java.io.FileInputStream; 4 import java.io.FileNotFoundException; 5 import java.io.IOException; 6 import java.io.InputStreamReader; 7 import java.util.Vector; 8 9 import jxl.Workbook; 10 import jxl.write.Label; 11 import jxl.write.WritableSheet; 12 import jxl.write.WritableWorkbook; 13 import jxl.write.WriteException; 14 import jxl.write.biff.RowsExceededException; 15 16 public class ExcelTest { 17 public static void main(String[] args) { 18 //writeData("Yannik","SheetOne",null); 19 writeData("MyTestExcel","FirstSheet",readData("MySrc.txt")); 20 } 21 22 23 24 public static VectorreadData(String filePath){ 25 26 FileInputStream fis; 27 InputStreamReader isr; 28 BufferedReader br; 29 30 Vector v = new Vector (); 31 32 33 try { 34 fis = new FileInputStream(new File(filePath)); 35 isr = new InputStreamReader(fis); 36 br = new BufferedReader(isr); 37 38 39 //For循环用于逐行读取txt的数据 40 try { 41 for(String s = br.readLine() ; s != null ; s = br.readLine()){ 42 String s1 = s.substring(0, 12); 43 String s2 = s.substring(13, 19); 44 String s3 = s.substring(20, 25); 45 String s4 = s.substring(26); 46 DataSrc src = new DataSrc(s1, s2, s3, s4); 47 v.add(src); 48 } 49 } catch (IOException e) { 50 // TODO Auto-generated catch block 51 e.printStackTrace(); 52 } 53 54 } catch (FileNotFoundException e) { 55 // TODO Auto-generated catch block 56 e.printStackTrace(); 57 } 58 59 return v; 60 } 61 62 /** 63 * 接受Vector数据,将数据写入到excel里边 64 * @param excelName 65 * @param sheetName 66 * @param vData 67 */ 68 public static void writeData(String excelName,String sheetName,Vector vData) { 69 try { 70 String sExcelName = excelName + ".xls"; 71 WritableWorkbook book = Workbook 72 .createWorkbook(new File(sExcelName)); 73 WritableSheet sheet = book.createSheet(sheetName, 0); 74 75 int i = 0; 76 for(DataSrc src : vData){ 77 Label label1 = new Label(0,i,src.getsDataFir()); 78 Label label2 = new Label(1,i,src.getsDataSec()); 79 Label label3 = new Label(2,i,src.getsDataThi()); 80 Label label4 = new Label(3,i,src.getsDataFor()); 81 82 try { 83 sheet.addCell(label1); 84 sheet.addCell(label2); 85 sheet.addCell(label3); 86 sheet.addCell(label4); 87 } catch (RowsExceededException e) { 88 // TODO Auto-generated catch block 89 e.printStackTrace(); 90 } catch (WriteException e) { 91 // TODO Auto-generated catch block 92 e.printStackTrace(); 93 } 94 95 i++; 96 } 97 98 book.write(); 99 try {100 book.close();101 } catch (WriteException e) {102 // TODO Auto-generated catch block103 e.printStackTrace();104 }105 } catch (IOException e) {106 // TODO Auto-generated catch block107 e.printStackTrace();108 }109 }110 111 112 113 }