2013-07-10 26 views
1

我正在尋找Groovy爲Excel文檔執行基本格式化命令的一些示例。我也想知道我在哪裏可以找到這些命令的存儲庫。Scriptom Groovy格式化Excel示例

你會如何:

插入一行

格式的短日期,時間單元等

大膽一整列或行

+0

POI不是問題而不是Scriptom? –

+0

如果您可以使用POI來做,則不需要3.9 –

回答

2

這個怎麼樣(有POI 3.9 )。

假設您在/tmp/test.xls中有輸入XLS文件,這應該進行所要求的修改,然後將工作簿寫入新文件/tmp/test2.xls。我已經添加了評論,所以希望它有意義:-)

@Grab('org.apache.poi:poi:3.9') 
import static org.apache.poi.ss.usermodel.CellStyle.* 
import static org.apache.poi.ss.usermodel.IndexedColors.* 
import org.apache.poi.hssf.usermodel.* 

// Open the spreadsheet 
new File('/tmp/test.xls').withInputStream { ins -> 
    new HSSFWorkbook(ins).with { workbook -> 
     // Select the first sheet 
     getSheetAt(0).with { sheet -> 

      // Insert a row at row 2 (zero indexed) 
      shiftRows(1, sheet.lastRowNum, 1) 

      // Add a value to this row in cell 1 
      getRow(1).with { row -> 
      createCell(0).with { cell -> 
       cell.setCellValue('12:32') 
      } 
      } 

      // Set the cell format to Time 
      // First we need to declare a style 
      def timeStyle = workbook.createCellStyle().with { style -> 
       dataFormat = HSSFDataFormat.getBuiltinFormat('h:mm:ss AM/PM') 
       style 
      } 
      // Then apply it to our cell 
      getRow(1).with { row -> 
       getCell(0).with { cell -> 
        cell.cellStyle = timeStyle 
       } 
      } 

      // Make row 1 bold 
      // First declare a style 
      def boldStyle = workbook.createCellStyle().with { style -> 
       style.font = workbook.createFont().with { f -> 
        f.boldweight = HSSFFont.BOLDWEIGHT_BOLD 
        f 
       } 
       style 
      } 
      // Then apply it to the row (I can only get this to work doing 
      // it to each cell in turn, setting the rowStyle seems to do nothing 
      getRow(0).with { row -> 
      (0..10).each { 
       getCell(it)?.cellStyle = boldStyle 
      } 
      } 
     } 

     // Write the modified workbook out to another xls file 
     new File('/tmp/test2.xls').withOutputStream { os -> 
      write(os) 
     } 
    } 
} 
+0

做得很好。我建議您將它添加到您的博客中,作爲Groovy中的POI用例。 :) – dmahapatro

+0

@dmahapatro好主意:-D博客的感覺被忽視了;-) –

+0

我每時每刻都在[挖掘](http://blog.bloidonia.com/)看看你在做什麼。 ;) – dmahapatro