java读取xls内容并写入txt
package document;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
/**
* 将excel中的内容复制到txt中
* @author DanielCooger
* <a href="mailto:tangjunfeng52099@gmail.com">daniel</a>
*/
public class Xls {
private static String date = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
private static String xls = "d:\\doc\\XLS" + date + ".txt";
private static String path="d:\\document\\1.xls";
public static void main(String[] args) {
?? new Xls().readExcel(path, xls, true);
}
//读取Excel内的数据并写入目标文件中
public boolean readExcel(String path,String xls,boolean append){
?? try {
??? InputStream is = new FileInputStream(path);
??? Workbook book = Workbook.getWorkbook(is);
??? Sheet sheet = book.getSheet(0);
??? // 得到所有的行数
??? Integer rows = sheet.getRows();
??? // 得到所有的列数
??? Integer colus = sheet.getColumns();
??? Cell cell;
??? for (int i = 0; i < rows; i++) {
???? for (int a = 0; a < colus; a++) {
????? cell = sheet.getCell(a, i);
????? new Xls().insert(xls, cell.getContents(), append);
???? /**
????? * 换行显示
????? * new Xls().insert(xls, cell.getContents()+"\r\n", append);
????? */
???? }
??? }
??? book.close();
??? return true;
?? } catch (Exception e) {
??? e.printStackTrace();
??? return false;
?? }
}
public void insert(String path, String content, boolean append) {
?? BufferedWriter bw;
?? File file;
?? try {
??? boolean addstr = append;
??? file = new File(path);
??? // 创建文件输出流写入文件
??? FileWriter fw = new FileWriter(file, addstr);
??? bw = new BufferedWriter(fw);
??? // 将文本内容写入文件
??? fw.write(content);
??? fw.flush();
??? fw.close();
?? } catch (Exception e) {
??? e.getMessage();
?? }
}
}