Dùng Groovy để đọc excel file

Tháng Ba 3, 2008

Đây là bài gốc từ mailing list của org.codehaus.groovy.userI got introduced to JExcelApi on the Groovy IRC channel this morning (http://www.andykhan.com/jexcelapi/)This is a Java package which lets you read an write Excel spreadsheets. It look pretty slick.

I have just hacked a Groovy script which reads an Excel spreadsheet and writes out the cell contents as a CSV


import java.io.File import jxl.Workbook

writeCsv = { | out, workBook, hide | 				for (sheetNumber in 0...workBook.numberOfSheets) { 					sheet = workBook.getSheet(sheetNumber)

out.println sheet.name

if (!(hide && sheet.settings.hidden)) { 						for (rowNumber in 0...sheet.rows) { 							row = sheet.getRow(rowNumber)

println row.findAll({!(hide && it.hidden)}).contents.join(', ') 						} 					} 				} 			}

writeCsv(System.out, Workbook.getWorkbook(new File("jxlrwtest.xls")),  false)
Some things to note:
sheet.settings.hidden
in Java this would have to be
sheet.getSettings().isHidden()
- Groovy’s bean support reduced the noise for
(sheetNumber in 0...workBook.numberOfSheets)

we use the ‘…’ form of the range to go to workBook.getNumberOfSheets() – 1 – again lots less noise

row.findAll({!(hide && it.hidden)}).contents

the findAll call returns a list of cell objects. We want to call getContents() on each cell object. We could use collect({ it.contents}) but someList.someProperty is equivalent to someList.collect({it.someProperty}) and a lot less noisy

If you download the package from the link above you will see a Java version of this in the demo package.

Entry Filed under: Groovy. Thẻ: .

Leave a Comment

Required

Required, hidden

Some HTML allowed:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <pre> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Trackback this post  |  Subscribe to the comments via RSS Feed


 

Tháng Ba 2008
T2 T3 T4 T5 T6 T7 CN
« Tháng 9   Tháng 6 »
 12
3456789
10111213141516
17181920212223
24252627282930
31  

a

Blogroll

Grails

Groovy

Bài viết mới

Lưu trữ

RSS Jason Rudolph (GRails)

RSS Raible Designs

RSS CodeJacked blog