PageRenderTime 56ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/src/main/java/com/taobao/itest/dbunit/dataset/excel/XlsDataSetWriter.java

https://github.com/qz267/automanx-api
Java | 261 lines | 113 code | 26 blank | 122 comment | 16 complexity | f843393f906ce40d438f12806e441583 MD5 | raw file
  1. /*
  2. *
  3. * The DbUnit Database Testing Framework
  4. * Copyright (C)2002-2008, DbUnit.org
  5. *
  6. * This library is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU Lesser General Public
  8. * License as published by the Free Software Foundation; either
  9. * version 2.1 of the License, or (at your option) any later version.
  10. *
  11. * This library is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. * Lesser General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Lesser General Public
  17. * License along with this library; if not, write to the Free Software
  18. * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  19. *
  20. */
  21. package com.taobao.itest.dbunit.dataset.excel;
  22. import java.io.IOException;
  23. import java.io.OutputStream;
  24. import java.math.BigDecimal;
  25. import java.util.Date;
  26. import org.apache.poi.hssf.usermodel.HSSFCell;
  27. import org.apache.poi.hssf.usermodel.HSSFCellStyle;
  28. import org.apache.poi.hssf.usermodel.HSSFDataFormat;
  29. import org.apache.poi.hssf.usermodel.HSSFRichTextString;
  30. import org.apache.poi.hssf.usermodel.HSSFRow;
  31. import org.apache.poi.hssf.usermodel.HSSFSheet;
  32. import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  33. import org.dbunit.dataset.Column;
  34. import org.dbunit.dataset.DataSetException;
  35. import org.dbunit.dataset.IDataSet;
  36. import org.dbunit.dataset.ITable;
  37. import org.dbunit.dataset.ITableIterator;
  38. import org.dbunit.dataset.ITableMetaData;
  39. import org.dbunit.dataset.datatype.DataType;
  40. import org.slf4j.Logger;
  41. import org.slf4j.LoggerFactory;
  42. /**
  43. * Writes an {@link IDataSet} to an XLS file or OutputStream.
  44. *
  45. * @author gommma (gommma AT users.sourceforge.net)
  46. * @author Last changed by: $Author: gommma $
  47. * @version $Revision: 915 $ $Date: 2008-12-07 14:17:25 +0100 (Sun, 07 Dec 2008)
  48. * $
  49. * @since 2.4.0
  50. */
  51. public class XlsDataSetWriter {
  52. public static final String ZEROS = "0000000000000000000000000000000000000000000000000000";
  53. /**
  54. * A special format pattern used to create a custom {@link HSSFDataFormat}
  55. * which marks {@link Date} values that are stored via POI to an XLS file.
  56. * Note that it might produce problems if a normal numeric value uses this
  57. * format pattern incidentally.
  58. */
  59. public static final String DATE_FORMAT_AS_NUMBER_DBUNIT = "####################";
  60. /**
  61. * Logger for this class
  62. */
  63. private static final Logger logger = LoggerFactory
  64. .getLogger(XlsDataSetWriter.class);
  65. private HSSFCellStyle dateCellStyle;
  66. /**
  67. * Write the specified dataset to the specified Excel document.
  68. */
  69. public void write(IDataSet dataSet, OutputStream out) throws IOException,
  70. DataSetException {
  71. logger.debug("write(dataSet={}, out={}) - start", dataSet, out);
  72. HSSFWorkbook workbook = new HSSFWorkbook();
  73. this.dateCellStyle = createDateCellStyle(workbook);
  74. int index = 0;
  75. ITableIterator iterator = dataSet.iterator();
  76. while (iterator.next()) {
  77. // create the table i.e. sheet
  78. ITable table = iterator.getTable();
  79. ITableMetaData metaData = table.getTableMetaData();
  80. HSSFSheet sheet = workbook.createSheet(metaData.getTableName());
  81. // write table metadata i.e. first row in sheet
  82. workbook.setSheetName(index, metaData.getTableName());
  83. HSSFRow headerRow = sheet.createRow(0);
  84. Column[] columns = metaData.getColumns();
  85. for (int j = 0; j < columns.length; j++) {
  86. Column column = columns[j];
  87. HSSFCell cell = headerRow.createCell(j);
  88. cell.setCellValue(new HSSFRichTextString(column.getColumnName()));
  89. }
  90. // write table data
  91. for (int j = 0; j < table.getRowCount(); j++) {
  92. HSSFRow row = sheet.createRow(j + 1);
  93. for (int k = 0; k < columns.length; k++) {
  94. Column column = columns[k];
  95. Object value = table.getValue(j, column.getColumnName());
  96. if (value != null) {
  97. HSSFCell cell = row.createCell(k);
  98. if (value instanceof Date) {
  99. setDateCell(cell, (Date) value, workbook);
  100. } else if (value instanceof BigDecimal) {
  101. setNumericCell(cell, (BigDecimal) value, workbook);
  102. } else if (value instanceof Long) {
  103. setDateCell(cell,
  104. new Date(((Long) value).longValue()),
  105. workbook);
  106. } else {
  107. cell.setCellValue(new HSSFRichTextString(DataType
  108. .asString(value)));
  109. }
  110. }
  111. }
  112. }
  113. index++;
  114. }
  115. // write xls document
  116. workbook.write(out);
  117. out.flush();
  118. }
  119. protected static HSSFCellStyle createDateCellStyle(HSSFWorkbook workbook) {
  120. HSSFDataFormat format = workbook.createDataFormat();
  121. short dateFormatCode = format.getFormat(DATE_FORMAT_AS_NUMBER_DBUNIT);
  122. HSSFCellStyle dateCellStyle = workbook.createCellStyle();
  123. dateCellStyle.setDataFormat(dateFormatCode);
  124. return dateCellStyle;
  125. }
  126. protected void setDateCell(HSSFCell cell, Date value, HSSFWorkbook workbook) {
  127. // double excelDateValue = HSSFDateUtil.getExcelDate(value);
  128. // cell.setCellValue(excelDateValue);
  129. // cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
  130. long timeMillis = value.getTime();
  131. cell.setCellValue((double) timeMillis);
  132. cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
  133. cell.setCellStyle(this.dateCellStyle);
  134. // System.out.println(HSSFDataFormat.getBuiltinFormats());
  135. // TODO Find out correct cell styles for date objects
  136. // HSSFCellStyle cellStyleDate = workbook.createCellStyle();
  137. // cellStyleDate.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy h:mm"));
  138. //
  139. // HSSFCellStyle cellStyleDateTimeWithSeconds =
  140. // workbook.createCellStyle();
  141. // cellStyleDateTimeWithSeconds.setDataFormat(HSSFDataFormat.getBuiltinFormat("h:mm:ss"));
  142. //
  143. // HSSFDataFormat dataFormat = workbook.createDataFormat();
  144. // HSSFCellStyle cellStyle = workbook.createCellStyle();
  145. // cellStyle.setDataFormat(dataFormat.getFormat("dd/mm/yyyy hh:mm:ss"));
  146. //
  147. // SimpleDateFormat formatter = new
  148. // SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
  149. // SimpleDateFormat formatter2 = new SimpleDateFormat("dd/MM/yyyy");
  150. // SimpleDateFormat formatter3 = new SimpleDateFormat("HH:mm:ss.SSS");
  151. //
  152. //
  153. // Date dateValue = (Date)value;
  154. // Calendar cal = null;
  155. //
  156. // // If it is a date value that does not have seconds
  157. // if(dateValue.getTime() % 60000 == 0){
  158. // // cellStyle = cellStyleDate;
  159. // cal=Calendar.getInstance();
  160. // cal.setTimeInMillis(dateValue.getTime());
  161. //
  162. // cell.setCellValue(cal);
  163. // cell.setCellStyle(cellStyle);
  164. // // cell.setCellValue(cal);
  165. // }
  166. // else {
  167. // // HSSFDataFormatter formatter = new HSSFDataFormatter();
  168. //
  169. // // If we have seconds assume that it is only h:mm:ss without date
  170. // // TODO Clean implementation where user can control date formats
  171. // would be nice
  172. // // double dateDouble = dateValue.getTime() % (24*60*60*1000);
  173. // cal = get1900Cal(dateValue);
  174. //
  175. // String formatted = formatter3.format(dateValue);
  176. // //TODO Format ...
  177. // // cellStyle = cellStyleDateTimeWithSeconds;
  178. // System.out.println("date formatted:"+formatted);
  179. // // HSSFRichTextString s = new HSSFRichTextString(formatted);
  180. // // cell.setCellValue(s);
  181. // cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
  182. // cell.setCellValue((double)dateValue.getTime());
  183. // cell.setCellStyle(cellStyleDateTimeWithSeconds);
  184. // }
  185. }
  186. protected void setNumericCell(HSSFCell cell, BigDecimal value,
  187. HSSFWorkbook workbook) {
  188. if (logger.isDebugEnabled())
  189. logger.debug(
  190. "setNumericCell(cell={}, value={}, workbook={}) - start",
  191. new Object[] { cell, value, workbook });
  192. cell.setCellValue(((BigDecimal) value).doubleValue());
  193. HSSFDataFormat df = workbook.createDataFormat();
  194. int scale = ((BigDecimal) value).scale();
  195. short format;
  196. if (scale <= 0) {
  197. format = df.getFormat("####");
  198. } else {
  199. String zeros = createZeros(((BigDecimal) value).scale());
  200. format = df.getFormat("####." + zeros);
  201. }
  202. if (logger.isDebugEnabled())
  203. logger.debug("Using format '{}' for value '{}'.",
  204. String.valueOf(format), value);
  205. HSSFCellStyle cellStyleNumber = workbook.createCellStyle();
  206. cellStyleNumber.setDataFormat(format);
  207. cell.setCellStyle(cellStyleNumber);
  208. }
  209. // public static Date get1900(Date date) {
  210. // Calendar cal = Calendar.getInstance();
  211. // cal.setTimeInMillis(date.getTime() % (24*60*60*1000));
  212. // cal.set(1900, 0, 1); // 1.1.1900
  213. // return cal.getTime();
  214. // }
  215. //
  216. // public static Calendar get1900Cal(Date date) {
  217. // Calendar cal = Calendar.getInstance();
  218. // cal.clear();
  219. // // long hoursInMillis = date.getTime() % (24*60*60*1000);
  220. // // long smallerThanDays = date.getTime() % (24*60*60*1000);
  221. // // cal.setTimeInMillis(date.getTime() % (24*60*60*1000));
  222. // cal.set(Calendar.SECOND, (int) (date.getTime() % (24*60*60*1000)) /
  223. // (1000) );
  224. // cal.set(Calendar.MINUTE, (int) (date.getTime() % (24*60*60*1000)) /
  225. // (1000*60) );
  226. // cal.set(Calendar.HOUR, (int) (date.getTime() % (24*60*60*1000)) /
  227. // (1000*60*60) );
  228. // // cal.set(1900, 0, 1); // 1.1.1900
  229. // System.out.println(cal.isSet(Calendar.DATE));
  230. // return cal;
  231. // }
  232. private static String createZeros(int count) {
  233. return ZEROS.substring(0, count);
  234. }
  235. }