1 19 package org.dbunit.dataset.excel; 20 21 import org.apache.poi.hssf.usermodel.HSSFCell; 22 import org.apache.poi.hssf.usermodel.HSSFRow; 23 import org.apache.poi.hssf.usermodel.HSSFSheet; 24 import org.apache.poi.hssf.usermodel.HSSFWorkbook; 25 import org.dbunit.dataset.*; 26 import org.dbunit.dataset.datatype.DataType; 27 28 import java.io.*; 29 30 39 public class XlsDataSet extends AbstractDataSet 40 { 41 private final ITable[] _tables; 42 43 46 public XlsDataSet(File file) throws IOException, DataSetException 47 { 48 this(new FileInputStream(file)); 49 } 50 51 54 public XlsDataSet(InputStream in) throws IOException, DataSetException 55 { 56 HSSFWorkbook workbook = new HSSFWorkbook(in); 57 _tables = new ITable[workbook.getNumberOfSheets()]; 58 for (int i = 0; i < _tables.length; i++) 59 { 60 _tables[i] = new XlsTable(workbook.getSheetName(i), 61 workbook.getSheetAt(i)); 62 } 63 } 64 65 68 public static void write(IDataSet dataSet, OutputStream out) 69 throws IOException, DataSetException 70 { 71 HSSFWorkbook workbook = new HSSFWorkbook(); 72 73 int index = 0; 74 ITableIterator iterator = dataSet.iterator(); 75 while(iterator.next()) 76 { 77 ITable table = iterator.getTable(); 79 ITableMetaData metaData = table.getTableMetaData(); 80 HSSFSheet sheet = workbook.createSheet(metaData.getTableName()); 81 82 workbook.setSheetName(index, metaData.getTableName(), HSSFWorkbook.ENCODING_UTF_16); 84 85 HSSFRow headerRow = sheet.createRow(0); 86 Column[] columns = metaData.getColumns(); 87 for (int j = 0; j < columns.length; j++) 88 { 89 Column column = columns[j]; 90 HSSFCell cell = headerRow.createCell((short)j); 91 cell.setEncoding(HSSFCell.ENCODING_UTF_16); 92 cell.setCellValue(column.getColumnName()); 93 } 94 95 for (int j = 0; j < table.getRowCount(); j++) 97 { 98 HSSFRow row = sheet.createRow(j + 1); 99 for (int k = 0; k < columns.length; k++) 100 { 101 Column column = columns[k]; 102 Object value = table.getValue(j, column.getColumnName()); 103 if (value != null) 104 { 105 HSSFCell cell = row.createCell((short)k); 106 cell.setEncoding(HSSFCell.ENCODING_UTF_16); 107 cell.setCellValue(DataType.asString(value)); 108 } 109 } 110 } 111 112 index++; 113 } 114 115 workbook.write(out); 117 out.flush(); 118 } 119 120 123 protected ITableIterator createIterator(boolean reversed) 124 throws DataSetException 125 { 126 return new DefaultTableIterator(_tables, reversed); 127 } 128 } 129 | Popular Tags |