我写的一个读取文件写入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);
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值