首页 > 代码库 > 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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。