我寫的一個讀取文件寫入excel的程序

我最近寫了一個程序,這個程序的需求是這樣的:

1 讀取一個txt文件,這個文件中有18萬筆數據;

2 文件中的每一行內容爲: 身份證號碼|姓名;

比如:

432323197709242312|曹輝

3 要求每200行寫入一個excel文件,並且excel有格式要求。

我是採用jxl.jar包來寫入excel文件的,因爲聽說這個包對中文的支持挺好的。

我寫的程序效率比較低,但是實現了需求中的功能。

開始測試了好幾次都報錯,數組越界,結果是由於數據中有的數據有問題,

有的行不是按照規定的格式來顯示的,有的行只有一個 ?號,或者該行爲亂碼,

或者該行沒有 | 分隔符。

我寫的JAVA程序如下:


package com.xjh.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.text.SimpleDateFormat;
import java.util.Date;

import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

public class CreateExcel5 {

public static void main(String[] args) throws Exception {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
print(sdf.format(new Date()));
for (int k = 1; k < 911; k++) {
BufferedReader in = new BufferedReader(new FileReader("c:\\wq_1.txt"));
WritableWorkbook book = Workbook.createWorkbook(new File("c:\\test" + k + ".xls"));
WritableSheet sheet = book.createSheet("xiejiaohui" + k, 0);
insertHead(book, sheet);
String s;
int i = 0;
while ((s = in.readLine()) != null) {
// if ( "".equals(s.trim()) || s.length() < 10) {
// if (s.length() < 10) {
// print(i + " xiejiaohui");
// if (s.length() > 0) {
// print(i + " xiejiaohui" + "[" + (200 * (k - 1)) + "]" + " " + "[" + (200 * k) + "] " + s);
// }
// continue;
// }
if (!s.contains("|")) {
if (s.length() > 0) {
print(i + " xiejiaohui" + "[" + (200 * (k - 1)) + "]" + " " + "[" + (200 * k) + "] " + s);
}
continue;
}
// if (k > 149) {
// print(i + " xiejiaohui" + "[" + (200 * (k - 1)) + "]" + " " + "[" + (200 * k) + "] " + s);
// }
if (i >= (200 * (k - 1)) && i < (200 * k)) {
String[] s2 = s.split("\\|");
sheet.addCell(new jxl.write.Number(0, i + 3 - (200 * (k - 1)), i + 1 - (200 * (k - 1))));
sheet.addCell(new Label(1, i + 3 - (200 * (k - 1)), s2[0]));
sheet.addCell(new Label(2, i + 3 - (200 * (k - 1)), s2[1]));
// print("i=" + i + " k=" + k + " " + s2[0] + " " + s2[1]);
} else {

}
i++;
}
book.write();
book.close();
in.close();
}
print(sdf.format(new Date()));
}

// 寫表頭
public static void insertHead(WritableWorkbook book, WritableSheet sheet)
throws Exception {
Date now = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String gmxx = "公民信息";
String zbsj = "製表時間 " + sdf.format(now);
String xh = "序號";
String zjh = "證件號";
String xm = "姓名";
sheet.addCell(new Label(0, 0, gmxx));
sheet.addCell(new Label(0, 1, zbsj));
sheet.addCell(new Label(0, 2, xh));
sheet.addCell(new Label(1, 2, zjh));
sheet.addCell(new Label(2, 2, xm));
}

public static void print(String s) {
System.out.println(s);
}

public static void print(int i) {
System.out.println(i);
}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章