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

groovy : poi 读取 Excel xlsx

时间:2014-10-01 22:55:41      阅读:459      评论:0      收藏:0      [点我收藏+]

标签:groovy   poi   excel   

下载 poi-bin-3.10-FINAL-20140208.zip 解压后

copy 
poi-3.10-FINAL-20140208.jar
poi-ooxml-3.10-FINAL-20140208.jar
poi-ooxml-schemas-3.10-FINAL-20140208.jar
ooxml-lib\dom4j-1.6.1.jar
ooxml-lib\dom4j-1.6.1.jar
ooxml-lib\xmlbeans-2.3.0.jar
    to D:\groovy-1.8.9\lib\

read_xlsx.groovy  代码如下

import javax.swing.JFileChooser
import javax.swing.filechooser.FileFilter
import javax.swing.filechooser.FileNameExtensionFilter
import java.io.File;
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 ReadExcel {
	static void main(args) {

		def getFilename ={
			def initDir='D:/'
			def chooser=new JFileChooser(initDir)
			def filter = new FileNameExtensionFilter('Excel', 'xlsx')
			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
		}
		
		def filename = getFilename() as String
		def outfile = new File(filename.replace('xlsx','txt'));
		def fp = outfile.newPrintWriter();
		println filename
		XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream(filename));

		(0..<wb.numberOfSheets).each{
		    XSSFSheet sheet = wb.getSheetAt(it)
		    int rows = sheet.physicalNumberOfRows
		    println " sheet:\"" + wb.getSheetName(it) + "\" has " + rows + " row(s)."
		    (0..<rows).each{ r ->
		        XSSFRow row = sheet.getRow(r)
		        if (row != null) {
		            int cells = row.physicalNumberOfCells
		            // println "\nROW " + row.rowNum + " has " + cells + " cell(s)."
		            (0..<cells).each{ c ->
		                XSSFCell cell = row.getCell(c)
		                if (cell == null)
		                	fp.print '\t';
		                else if (cell.getCellType() == XSSFCell.CELL_TYPE_BOOLEAN)
		                	fp.print cell.getBooleanCellValue()+'\t';
		                else if (cell.getCellType() == XSSFCell.CELL_TYPE_NUMERIC)
		                	fp.print cell.getNumericCellValue()+'\t';
		                else
		                	fp.print cell.getStringCellValue()+'\t';
		            }
		            fp.println '';
		        }
		    }  
		}
		fp.flush();
		fp.close();
		
	}
}


groovy : poi 读取 Excel xlsx

标签:groovy   poi   excel   

原文地址:http://blog.csdn.net/belldeep/article/details/39721345

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