2010年12月25日土曜日

H2 DatabaseとApache POIでExcelブックのセルにコメントをセットして保存する関数を作成する

H2 DatabaseとApache POIでExcelブックのセルにコメントをセットして保存する関数を作成するには、以下のスクリプトを実行します。

create alias if not exists poi_update_set_comment as $$ 
import java.io.*;
import java.sql.*;
import java.text.*;
import org.h2.tools.*;
import org.apache.poi.ss.usermodel.*;
@CODE
int poi_update_set_comment(
String inFile, String outFile, String sheetName,
int row, int column, String author, String comment)
throws Exception
{
if( inFile == null ){
return -1;
}
if( outFile == null ){
return -1;
}
if( author == null ){
author = "";
}
if( comment == null ){
return -1;
}
Workbook workbook = WorkbookFactory.create(new FileInputStream(inFile));
Sheet sheet = workbook.getSheet(sheetName);
if( sheet == null ){
return -1;
}

Row rowobj = sheet.getRow(row);
if( rowobj == null ){
rowobj = sheet.createRow(row);
}
Cell cell = rowobj.getCell(column);
if( cell == null ){
cell = rowobj.createCell(column);
}
// コメントの作成
CreationHelper ch = workbook.getCreationHelper();
ClientAnchor anchor = ch.createClientAnchor();
Drawing drawing = sheet.createDrawingPatriarch();
Comment commentObj = drawing.createCellComment(anchor);
commentObj.setString(ch.createRichTextString(comment));
commentObj.setAuthor(author);
cell.setCellComment(commentObj);

workbook.write(new FileOutputStream(outFile));
return 0;
}
$$


実行例
select poi_update_set_comment('c:\share\test1.xlsx', 'c:\share\test1e.xlsx', 'シート1', 2, 0, 'test1', 'コメントです');


入力Excel(test1.xlsx)


出力Excel(test1e.xlsx)


※システム環境変数CLASSPATHにtools.jarと以下のPOI関連のjarを追加しておくこと。
・poi-3.7-20101029.jar
・poi-ooxml-3.7-20101029.jar
・poi-ooxml-schemas-3.7-20101029.jar
・commons-logging-1.1.jar
・log4j-1.2.13.jar;
・geronimo-stax-api_1.0_spec-1.0.jar
・xmlbeans-2.3.0.jar
・dom4j-1.6.1.jar

○動作環境
JDK6 Update 22, H2 Database 1.2.147 (2010-11-21), Apache POI 3.7
○関連情報
・H2 Databaseに関する他の記事はこちらを参照してください。

0 件のコメント:

コメントを投稿