首页 > 代码库 > groovy : poi ExcelExtractor

groovy : poi ExcelExtractor

参考 file://poi-3.10-FINAL/docs/spreadsheet/quick-guide.html#TextExtraction

Excel2txt.groovy 代码如下

import java.io.File;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.extractor.ExcelExtractor;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Row;

class Excel2txt {
	
	static void main(args) {
		if (args.size()!=1){
			println ' usage: groovy Excel2txt file.xls '
			return;
		} else {
			def filename = args[0];
			if (filename==null || filename=='') return;
			def idx = filename.lastIndexOf('.');
			def ext = filename.substring(idx);
			if (ext != '.xls'){
				println ' filename is not .xls ?'
				return;
			}
			def fis = new FileInputStream(filename);
			def outfile = new File(filename.replace('xls','txt'));
			def fp = outfile.newPrintWriter();
			def wb = new HSSFWorkbook(new POIFSFileSystem(fis));
			def extractor = new ExcelExtractor(wb);
			
			extractor.setFormulasNotResults(true);
			extractor.setIncludeSheetNames(false);
			extractor.setIncludeCellComments(true);
			String text = extractor.getText();
			fp.println text
			fp.flush();
			fp.close();
		}
	}
}


groovy : poi ExcelExtractor