/*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();
}
}
}