write_xlsx.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.xssf.usermodel.XSSFDataFormat; import org.apache.poi.xssf.usermodel.XSSFCellStyle; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; 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 工作簿 XSSFWorkbook workbook = new XSSFWorkbook(); XSSFSheet sheet = workbook.createSheet(shname); // 用于格式化单元格的数据 XSSFDataFormat format = workbook.createDataFormat(); // 设置单元格类型 XSSFCellStyle cellStyle = workbook.createCellStyle(); cellStyle.setDataFormat(format.getFormat("0.00;-0.00")); XSSFRow row = null; XSSFCell 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 Text2xlsx(); app.write_xlsx(filename); } }
直接运行 groovy write_xlsx
时间: 2024-10-03 04:58:31