运行此程序需要添加一个jar包
下载地址
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.StringTokenizer;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
public class FileToExcel {
public static void main(String[] args) throws Exception {
writeToExcel("D:\\output.txt", "D:\\output.xls");
System.out.println("finished!");
}
public static void writeToExcel(String inFile, String outExcel) throws Exception {
//打开文件
WritableWorkbook book= Workbook.createWorkbook(new File(outExcel));
//生成名为“第一页”的工作表,参数0表示这是第一页
WritableSheet sheet=book.createSheet("第一页",0);
//在Label对象的构造子中指名单元格位置是第一列第一行(0,0)
//以及单元格内容为test
//Label label=new Label(0,0,"测试");
//将定义好的单元格添加到工作表中
//sheet.addCell(label);
//jxl.write.Number number = new jxl.write.Number(1,0,789.123);
//sheet.addCell(number);
//jxl.write.Label s=new jxl.write.Label(1, 2, "三十三");
//sheet.addCell(s);
//写入数据并关闭文件
Label label = null;
String s1 = readFile(inFile);
StringTokenizer st1 = new StringTokenizer(s1, "\n");
for(int i=0;st1.hasMoreElements();i++) {
String s2 = st1.nextToken();
StringTokenizer st2 = new StringTokenizer(s2, " \t");
for(int j=0;st2.hasMoreElements();j++) {
String s = st2.nextToken();
label=new Label(j,i, "" + s);
sheet.addCell(label);
}
}
book.write();
book.close(); //最好在finally中关闭,此处仅作为示例不太规范
}
private static String readFile(String filename) throws Exception {
BufferedReader reader = new BufferedReader(new FileReader(filename));
String ans = "", line = null;
while ((line = reader.readLine()) != null) {
ans += line + "\r\n";
}
reader.close();
return ans;
}
}
posted on 2015-04-15 22:11
marchalex 阅读(405)
评论(0) 编辑 收藏 所属分类:
java小程序