king123654789 发表于 2013-1-26 15:15:01

从excel获取数据写入txt文本中

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;


public class ParseInTxt {
   private File result = null;
   private FileWriter writer;
   private PrintWriter pw;
   boolean bool;
   // path动态指定路径
public void createTxT(String path){ // 创建新的txt数据文件
    bool = false;
    result = new File(path);
      try {
    result.createNewFile();// 在本地创建一个txt文件
    bool = true;
       } catch (IOException e) {
    bool = false;
    System.err.println(e);
   }
   if(bool){
    try {
    writer = new FileWriter(path);
    } catch (IOException e) {
   System.err.println(e);
    }
    try {
   pw = new PrintWriter(path);
    } catch (FileNotFoundException e) {
   System.err.println(e);
    }
   }
   }
   public void aLine(List<Info> in) { //写入一个List集
    for(int i=0;i<in.size();i++){
       pw.println(in.get(i).getUserName()+"            "+in.get(i).getUserPass());
    }
   }
   /*public void aLint(String in){// 写入一行
    pw.println(in);
   }*/
   public void finish() { //关闭输入流,将文字从缓存写入文件
    try{
         pw.flush();
         writer.close();
    }catch (IOException iox){
         System.err.println(iox);
    }
   }
   public static List<Info> readExcel(String pathname) {
List<Info> list = new ArrayList<Info>();
try {         
//打开文件 6
Workbook book = Workbook.getWorkbook(new File(pathname)) ;
//取得第一个sheet
Sheet sheet = book.getSheet(0);
          //取得行数
            int rows = sheet.getRows();
            for(int i = 1; i < rows; i++) {
            Info info = new Info();
            //getCell(列,行)
            info.setUserName(sheet.getCell(0,i).getContents());
            System.out.println("用户名:"+sheet.getCell(0,i).getContents());
            
            info.setUserPass(sheet.getCell(1,i).getContents());
            System.out.println("密码:"+sheet.getCell(1,i).getContents());
            
            info.setTrueName(sheet.getCell(2,i).getContents());
            System.out.println("真实名称:"+sheet.getCell(2,i).getContents());
            
            list.add(info);
            }
            
            //关闭文件
            book.close();
            } catch (BiffException e) {
            e.printStackTrace();
            } catch (IOException e) {
         e.printStackTrace();
      }
return list;   
}
   
   public static void main(String[] args) {
   ParseInTxt c = new ParseInTxt();
    c.createTxT("C:\\myTest.txt");//需要生成的文件路径
    List<Info> in=readExcel("D:\\test.xls");
c.aLine(in);//list类型
    c.finish();
}
}
页: [1]
查看完整版本: 从excel获取数据写入txt文本中