程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> 關於JAVA >> java從excel獲取數據寫入txt文本中實現代碼

java從excel獲取數據寫入txt文本中實現代碼

編輯:關於JAVA
 

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. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved