码迷,mamicode.com
首页 > 其他好文 > 详细

groovy : poi 导出 Excel xlsx

时间:2017-06-10 10:47:04      阅读:209      评论:0      收藏:0      [点我收藏+]

标签:turn   ted   文件   apach   exce   []   apache   port   mat   

參考 file:///poi-3.10-FINAL/docs/spreadsheet/how-to.html#sxssf

text2xlsx.groovy 代码例如以下

package xlsx;
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.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellReference;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;

class Text2xlsx {
		
	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 write_xlsx(String filename) {
		if (filename==null || filename==‘‘) return;
		def idx = filename.lastIndexOf(‘.‘);
		def fname = filename.substring(0,idx);
		def file2 = fname +".xlsx" as String;
		def shname = fname.tokenize(‘\\‘)[-1] as String;
		println "${file2} , ${shname}"

		// 创建新的Excel 工作簿
		SXSSFWorkbook workbook = new SXSSFWorkbook(100);   
		Sheet sheet = workbook.createSheet(shname);

		int n=0;
		int i=0; // rowIndex
		int j=0;
		def alist =[]
		new File(filename).eachLine{ line ->
			alist = line.split(/,/);
			n = alist.size();  
			if (n >1){
				Row row = sheet.createRow(i); // 创建新行(row)
				for(j=0; j<n; j++){
					row.createCell(j).setCellValue((String)alist[j]); // 创建单元格
						
				}
				i ++ ;
			}
		}
		// 创建文件输出流。输出电子表格
		try {
			def fout = new FileOutputStream(new File(file2));
			workbook.write(fout);
			fout.close();
			workbook.dispose();
		} 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 Text2xlsx();
		app.write_xlsx(filename);
	}
}


groovy : poi 导出 Excel xlsx

标签:turn   ted   文件   apach   exce   []   apache   port   mat   

原文地址:http://www.cnblogs.com/cxchanpin/p/6977776.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!