/*txt中的内容是一列一列的形式,如下形式
"001","张三","男","北京","284969587","23"
"002","李四","男","山东","130655869","22"
"003","王五","男","江苏","111726522","23"
将其写入到excel中。
若用Java代码实现以上任务,首先要有jxl.jar包,它是通过java操作excel表格的工具类
库 。
从网上下载jxl.jar后,要搭建环境,既可以将jxl.jar放入到classpath中,也可以在
eclipse中通过buidpath来添加。
源代码如下:
package txtToExcel;*/
package com.util;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
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 Test1 {
public static void readFileByLines(String fileName) throws IOException,
RowsExceededException, WriteException {
// 打开文件
WritableWorkbook book = Workbook.createWorkbook(new File(
"D://data3.xls"));
// 生成名为“第一页”的工作表,参数0表示这是第一页
WritableSheet sheet = book.createSheet("第一页", 0);
// 读入txt中的内容
File file = new File(fileName);
FileInputStream fis = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(fis, "gbk");
BufferedReader reader = null;
try {
reader = new BufferedReader(isr);
String tempString = null;
// 一次读入一行,直到读入null为文件结束
int i = 0;
while ((tempString = reader.readLine()) != null) {
System.out.println(tempString);
String[] str = tempString.split(",");
// Label[] label = null;
for (int j = 0; j < str.length; j++) {
// 在Label对象的构造子中指名单元格位置是第j列第i行(j,i)以及单元格内容为str[j]
Label label = new Label(j, i, str[j]);
// 将定义好的单元格添加到工作表中
sheet.addCell(label);
}
i++;
}
// 写入数据并关闭文件
book.write();
try {
book.close();
} catch (WriteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
reader.close();
}
}
}
public static void main(String[] args) throws RowsExceededException,
WriteException {
try {
readFileByLines("D://data.txt");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}