package test; import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List; 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 ConvertTxtExcel {
private static List<Account> list = new ArrayList<Account>();
private final static String TXTFILENAME = "F:\\\\myTxt.txt";
private final static String EXCELFILENAME = "F:\\\\myExcel.xls"; public static void main(String[] args) {
getTxt();
txtToExcel();
} private static void txtToExcel() {
WritableWorkbook wwk = null;
try {
wwk = Workbook.createWorkbook(new File(EXCELFILENAME));
WritableSheet ws = wwk.createSheet("Test1", 0);
Label label1 = new Label(0, 0, "id");
Label label2 = new Label(1, 0, "user");
Label label3 = new Label(2, 0, "paw");
Label label4 = new Label(3, 0, "age");
// 将定义好的单元格添加到工作表中
ws.addCell(label1);
ws.addCell(label2);
ws.addCell(label3);
ws.addCell(label4);
/*
* 生成一个保存数字的单元格 必须使用Number的完整包路径,否则有语法歧义
*/
for (int i = 0; i < list.size(); i++) {
Account p = list.get(i);
jxl.write.Number id = new jxl.write.Number(0, (i + 1), p.getId());
Label label5 = new Label(1, (i + 1), p.getUser());
Label label6 = new Label(2, (i + 1), p.getPaw());
jxl.write.Number age = new jxl.write.Number(3, (i + 1), p.getAge());
ws.addCell(id);
ws.addCell(label5);
ws.addCell(label6);
ws.addCell(age);
}
wwk.write();
wwk.close();
} catch (IOException e) {
e.printStackTrace();
} catch (RowsExceededException e) {
e.printStackTrace();
} catch (WriteException e) {
e.printStackTrace();
}
System.out.println("完成");
} private static List<Account> getTxt() {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(TXTFILENAME), "utf-8"));
String line = "";
while ((line = br.readLine()) != null) {
//TXT里面的数据都是用-隔开的,例如:1-haha-123123-12
String[] arr = line.split("-");
Account account = new Account(Integer.parseInt(arr[0]), arr[1], arr[2], Integer.parseInt(arr[3]));
list.add(account);
}
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return list;
}
}
ConvertTxtExcel
结果:
注意事项:需要导 jxl.jar