首页 > 代码库 > groovy : poi 导出 Excel

groovy : poi 导出 Excel

write_xls.groovy 代码如下

package xls;
import javax.swing.JFileChooser
import javax.swing.filechooser.FileFilter
import javax.swing.filechooser.FileNameExtensionFilter
import java.io.File
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFCellStyle; 
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;

class Text2xls  {
		
	private static String getFilename(String initDir) {
		if (initDir==null || initDir=='') initDir='.';
		def chooser=new JFileChooser(initDir)
		def filter = new FileNameExtensionFilter('Text', 'txt')
		chooser.setFileFilter(filter)
		chooser.setDialogTitle("Open")
		if(chooser.showSaveDialog() == JFileChooser.APPROVE_OPTION)
			return chooser.getSelectedFile()
		else if(chooser.showSaveDialog() == JFileChooser.CANCEL_OPTION)
			return null
		else
			return null
	}

	void writeExcel(String filename) {
		if (filename==null || filename=='') return;
		def idx = filename.lastIndexOf('.');
		def fname = filename.substring(0,idx);
		def file2 = fname +".xls" as String;
		def shname = fname.tokenize('\\')[-1] as String;
		println "${file2} , ${shname}"

		// 创建新的Excel 工作簿  
		HSSFWorkbook workbook = new HSSFWorkbook();
		HSSFSheet sheet = workbook.createSheet(shname);
		// 用于格式化单元格的数据  
		HSSFDataFormat format = workbook.createDataFormat();
		// 设置单元格类型  
    HSSFCellStyle cellStyle = workbook.createCellStyle();
    cellStyle.setDataFormat(format.getFormat("0.00;-0.00"));
		HSSFRow row = null;
		HSSFCell cell = null;
		int n=0;
		int i=0; // rowIndex
		int j=0;
		def alist =[]
		new File(filename).eachLine{ line ->
			alist = line.tokenize('\t');
			n = alist.size();  
			if (n >0){
				row = sheet.createRow(i); // 创建新行(row)
				for(j=0; j<n; j++){
					cell = row.createCell(j); // 创建单元格
					if (alist[j]!=null)
						if (alist[j]=~/^-?[0-9]+(.[0-9]+)?$/){ // 是数字
							cell.setCellValue(new BigDecimal(alist[j]));							
							cell.setCellStyle(cellStyle);
						} else {
							cell.setCellValue((String)alist[j]);
						}
				}
				i ++ ;
			}
		}
		// 创建文件输出流,输出电子表格
		try {
			OutputStream fout = new FileOutputStream(file2);
			workbook.write(fout);
			fout.close();
		} catch(e){
			println e;
		}
	}

	static void main(args) {
		def filename =null;		
		if (args.size()==1)
			filename = getFilename(args[0]);
		else
			filename = getFilename('.');
		if (filename==null) return;
		def app = new Text2xls();
		app.writeExcel(filename);
	}
}


groovy : poi 导出 Excel