PageRenderTime 145ms CodeModel.GetById 40ms RepoModel.GetById 11ms app.codeStats 0ms

/util/src/main/java/com/abc/myproject/common/SimpleWorkbook.java

https://github.com/ronesp86/MyProject
Java | 278 lines | 200 code | 38 blank | 40 comment | 25 complexity | 18e2225138f643531073f515c348c26e MD5 | raw file
Possible License(s): Apache-2.0
  1. package com.abc.myproject.common;
  2. import java.io.IOException;
  3. import java.io.InputStream;
  4. import java.io.OutputStream;
  5. import java.util.Date;
  6. import java.util.HashMap;
  7. import java.util.List;
  8. import java.util.Map;
  9. import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  10. import org.apache.poi.ss.usermodel.Cell;
  11. import org.apache.poi.ss.usermodel.CellStyle;
  12. import org.apache.poi.ss.usermodel.CellValue;
  13. import org.apache.poi.ss.usermodel.DataFormatter;
  14. import org.apache.poi.ss.usermodel.Font;
  15. import org.apache.poi.ss.usermodel.Row;
  16. import org.apache.poi.ss.usermodel.Sheet;
  17. import org.apache.poi.ss.usermodel.Workbook;
  18. import org.apache.poi.ss.usermodel.WorkbookFactory;
  19. import com.google.common.collect.Lists;
  20. /**
  21. * Simple apache poi wrapper. Write only support ".xls". Read support ".xls and .xlsx".
  22. *
  23. * <pre>
  24. * <b>Example:</b>
  25. *
  26. * Create:
  27. * <code>SimpleWorkbook workbook = new SimpleWorkbook();
  28. * workbook.createTitleRow("sheet01", "title01", "title02");
  29. * for (short i = 1; i <= (short) 10; i++) {
  30. * workbook.setData("sheet01", i, 0, "row:" + i + ",col:" + 0);
  31. * workbook.setData("sheet01", i, 1, "row:" + i + ",col:" + 1);
  32. * }
  33. * String filename = "SimpleWorkbookTestFile." + workbook.getExtension();
  34. *
  35. * FileOutputStream fos = new FileOutputStream(filename);
  36. * workbook.write(fos);
  37. * fos.close();
  38. * </code>
  39. * Read:
  40. * FileInputStream fis = new FileInputStream(filename);
  41. * SimpleWorkbook fileInDisk = SimpleWorkbook.fromStream(fis);
  42. * fis.close();
  43. * List<String> values = fileInDisk.values(new RowMapper<String>() {
  44. *
  45. *
  46. * public String mapRow(List<String> celValues) {
  47. * return celValues.get(0) + "******" + celValues.get(1);
  48. * }
  49. * });
  50. * for (String v : values) {
  51. * System.out.println(v);
  52. * }
  53. *
  54. *
  55. * </pre>
  56. *
  57. * @author ezhengx
  58. *
  59. */
  60. public class SimpleWorkbook {
  61. private static final String YYYY_MM_DD = "yyyy/MM/dd";
  62. public enum FontStyle {
  63. NORMAL, BOLD, ITALICS, BOLD_ITALICS
  64. }
  65. private final Workbook wb;
  66. private final Map<String, Sheet> sheets;
  67. private Map<FontStyle, CellStyle> styles;
  68. private CellStyle dateStyle;
  69. public SimpleWorkbook() {
  70. this(new HSSFWorkbook());
  71. }
  72. private SimpleWorkbook(Workbook workbook) {
  73. wb = workbook;
  74. sheets = new HashMap<String, Sheet>();
  75. setupFonts();
  76. setupDateStyle();
  77. }
  78. private void setupDateStyle() {
  79. dateStyle = wb.createCellStyle();
  80. String dateformat = System.getProperty("sdp.export.date.format");
  81. dateStyle.setDataFormat(wb.getCreationHelper().createDataFormat().getFormat(
  82. dateformat == null ? YYYY_MM_DD : dateformat));
  83. }
  84. private void setupFonts() {
  85. styles = new HashMap<FontStyle, CellStyle>();
  86. for (FontStyle fs : FontStyle.values()) {
  87. CellStyle style = wb.createCellStyle();
  88. Font font = wb.createFont();
  89. switch (fs) {
  90. case BOLD:
  91. font.setBoldweight(Font.BOLDWEIGHT_BOLD);
  92. break;
  93. case BOLD_ITALICS:
  94. font.setBoldweight(Font.BOLDWEIGHT_BOLD);
  95. font.setItalic(true);
  96. break;
  97. case ITALICS:
  98. font.setItalic(true);
  99. break;
  100. case NORMAL:
  101. break;
  102. }
  103. style.setFont(font);
  104. styles.put(fs, style);
  105. }
  106. }
  107. private void createSheet(String name) {
  108. if (!sheets.containsKey(name)) {
  109. sheets.put(name, wb.createSheet(name));
  110. }
  111. }
  112. public void setData(String sheetName, int rowNr, int colNr, String data) {
  113. Sheet sheet = getOrCreateSheet(sheetName);
  114. Cell cell = getOrCreateCell(sheet, rowNr, colNr);
  115. cell.setCellValue(wb.getCreationHelper().createRichTextString(data));
  116. }
  117. public void setData(String sheetName, int rowNr, int colNr, double data) {
  118. Sheet sheet = getOrCreateSheet(sheetName);
  119. Cell cell = getOrCreateCell(sheet, rowNr, colNr);
  120. cell.setCellValue(data);
  121. }
  122. public void setData(String sheetName, int rowNr, int colNr, Date data) {
  123. Sheet sheet = getOrCreateSheet(sheetName);
  124. Cell cell = getOrCreateCell(sheet, rowNr, colNr);
  125. cell.setCellValue(data);
  126. cell.setCellStyle(dateStyle);
  127. }
  128. public void setData(String sheetName, int rowNr, int colNr, boolean data) {
  129. Sheet sheet = getOrCreateSheet(sheetName);
  130. Cell cell = getOrCreateCell(sheet, rowNr, colNr);
  131. cell.setCellValue(data);
  132. }
  133. public void setCellFontStyle(String sheetName, int rowNr, int colNr, FontStyle fs) {
  134. Sheet sheet = getOrCreateSheet(sheetName);
  135. getOrCreateCell(sheet, rowNr, colNr).setCellStyle(styles.get(fs));
  136. }
  137. public void createTitleRow(String sheetName, String... columnNames) {
  138. for (int i = 0; i < columnNames.length; i++) {
  139. setData(sheetName, 0, i, columnNames[i]);
  140. setCellFontStyle(sheetName, 0, i, FontStyle.BOLD);
  141. }
  142. }
  143. private Sheet getOrCreateSheet(String sheetName) {
  144. if (!sheets.containsKey(sheetName)) {
  145. createSheet(sheetName);
  146. }
  147. return sheets.get(sheetName);
  148. }
  149. private Row getOrCreateRow(Sheet sheet, int rowNr) {
  150. Row row = sheet.getRow(rowNr);
  151. if (row == null) {
  152. row = sheet.createRow(rowNr);
  153. }
  154. return row;
  155. }
  156. private Cell getOrCreateCell(Sheet sheet, int rowNr, int colNr) {
  157. Row row = getOrCreateRow(sheet, rowNr);
  158. Cell cell = row.getCell(colNr);
  159. if (cell == null) {
  160. cell = row.createCell(colNr);
  161. }
  162. return cell;
  163. }
  164. public void write(OutputStream os) throws IOException {
  165. wb.write(os);
  166. os.flush();
  167. }
  168. public String getExtension() {
  169. return "xls";
  170. }
  171. public interface RowMapper<T> {
  172. T mapRow(List<String> celValues);
  173. }
  174. public <T> List<T> values(RowMapper<T> mapper) {
  175. Sheet sheet = null;
  176. Row row = null;
  177. List<T> bookData = Lists.newArrayList();
  178. DataFormatter formatter = new DataFormatter();
  179. int numSheets = this.wb.getNumberOfSheets();
  180. for (int i = 0; i < numSheets; i++) {
  181. sheet = this.wb.getSheetAt(i);
  182. if (sheet.getPhysicalNumberOfRows() > 0) {
  183. int lastRowNum = sheet.getLastRowNum();
  184. for (int j = 0; j <= lastRowNum; j++) {
  185. row = sheet.getRow(j);
  186. List<String> cellValues = Lists.newArrayList();
  187. int lastCellNum = row.getLastCellNum();
  188. for (int k = 0; k <= lastCellNum; k++) {
  189. cellValues.add(formatter.formatCellValue(row.getCell(k)));
  190. }
  191. bookData.add(mapper.mapRow(cellValues));
  192. }
  193. }
  194. }
  195. return bookData;
  196. }
  197. public static SimpleWorkbook fromStream(InputStream workbookStream) {
  198. SimpleWorkbook sWorkbook = null;
  199. try {
  200. sWorkbook = new SimpleWorkbook(WorkbookFactory.create(workbookStream));
  201. } catch (Exception e) {
  202. e.printStackTrace();
  203. }
  204. return sWorkbook;
  205. }
  206. public static SimpleWorkbook mergeWorkbook(SimpleWorkbook... workbooks){
  207. SimpleWorkbook mergeWorkbook = new SimpleWorkbook();
  208. int num = 0;
  209. for(SimpleWorkbook workbook : workbooks){
  210. int numSheets = workbook.getWb().getNumberOfSheets();
  211. for (int i = 0; i < numSheets; i++) {
  212. Sheet sheet = workbook.getWb().getSheetAt(i);
  213. String sheetName = sheet.getSheetName();
  214. if(mergeWorkbook.getWb().getSheet(sheetName) != null){
  215. num ++;
  216. sheetName = sheetName + "(" + num + ")";
  217. }
  218. mergeWorkbook.createSheet(sheetName);
  219. if (sheet.getPhysicalNumberOfRows() > 0) {
  220. int lastRowNum = sheet.getLastRowNum();
  221. for (int j = 0; j <= lastRowNum; j++) {
  222. Row row = sheet.getRow(j);
  223. if(row != null){
  224. int lastCellNum = row.getLastCellNum();
  225. for (int k = 0; k <= lastCellNum; k++) {
  226. Cell cell = row.getCell(k);
  227. String cellValue = cell == null ? "" : cell.toString();
  228. mergeWorkbook.setData(sheetName, j+1, k, cellValue == null ? "" : cellValue);
  229. }
  230. }
  231. }
  232. }
  233. }
  234. }
  235. return mergeWorkbook;
  236. }
  237. public Workbook getWb() {
  238. return wb;
  239. }
  240. }