#author("2023-05-22T09:35:47+00:00","","")
#author("2023-07-20T05:38:13+00:00","","")
// 下階層用テンプレート
#topicpath
----
//ここにコンテンツを記述します。
#contents

**データをExcel形式でエクスポートする [#i13eb1e2]
さて、[[Java/DBUnit/XMLでImport,Exportする]] でxmlファイルをimport/exportできるのはわかりましたが、このxmlファイルを手で作らなくてはいけないんだったら、結局面倒ですね。つうことで今度はExcel形式でExportします。AntタスクにはExcel関連のものはないっぽく、プログラムを作る必要があります。っても以下の感じ。

 public static void main(String[] args) {
   DOMConfigurator.configure("log4j.xml");
   IDatabaseConnection con = null;
   try {
     con = getConnection();
     IDataSet dataset = con.createDataSet();
     XlsDataSet.write(dataset, new FileOutputStream("export.xls"));
   } catch (Exception e) {
     e.printStackTrace();
   } finally {
     try {
       if (con != null) {
         con.close();
       }
     } catch (SQLException e) {
       e.printStackTrace();
     }
   }
 }

getConnectionは以下のようにしました。DataSourceを作るのが面倒だったのでDIでInjectionしてます。

 protected static IDatabaseConnection getConnection() throws Exception {
   ApplicationContext context = new ClassPathXmlApplicationContext(
       new String[] { "hibernate-spring_test.xml" });
   DataSource datasource = (DataSource) context.getBean("dataSource");
   return new DatabaseConnection(datasource.getConnection(), "webdb1");<-schema名
 }

でdataSourceのJavaBeansはorg.apache.commons.dbcp.BasicDataSourceを使ってこんな感じ。

-beans.xmlの中身。
 <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" 
   destroy-method="close">
   <property name="driverClassName">
     <value>com.mysql.jdbc.Driver</value>
   </property>
   <property name="url">
     <value>jdbc:mysql://192.168.10.5/webdb1?useUnicode=true&amp;characterEncoding=ujis</value>
   </property>
   <property name="username"><value>xxxx</value></property>
   <property name="password"><value>xxxx</value></property>
 </bean>


実行するとexport.xlsが出力されます。内容は以下の通り

#ref(export.png)

テーブルがExcelのシートになってるところがシブイです。




**データをExcelからインポートする [#y217c7fb]
さて最後です。Excelファイルをimportします。さっきのxlsファイルをインポートデータとして使用します。import.xlsとしました。

 public static void main(String[] args) {
   DOMConfigurator.configure("log4j.xml");
   IDatabaseConnection con = null;
   try {
     con = getConnection(); // <- Exportのときと同じ
     IDataSet dataset = new XlsDataSet(new File("import.xls"));
     DatabaseOperation.CLEAN_INSERT.execute(con, dataset);
     // deleteしてからinsert
   } catch (Exception e) {
     e.printStackTrace();
   } finally {
     try {
       if (con != null) {
         con.close();
       }
     } catch (SQLException e) {
       e.printStackTrace();
     }
   }
 }
実行すれば、全件Delete後import.xlsの内容がテーブルに反映されます。簡単ですね。


**つかってみて [#f2bd6603]
これでテストデータをオラーってExcelで作成して、ドカンとimportができそうです。結構便利です。


**関連リンク [#d325a0e3]
-Java/Ant/DBをExcelにExportするAntタスク


----
この記事は
#vote(おもしろかった[61],そうでもない[3])
#vote(おもしろかった[62],そうでもない[3])

#comment
#topicpath


SIZE(10){現在のアクセス:&counter;}

トップ   編集 差分 バックアップ 添付 複製 名前変更 リロード   新規 一覧 単語検索 最終更新   ヘルプ   最終更新のRSS