Java实现将txt中的内容写入到excel中

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值