ExcelUtil.java 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. package com.gyee.alarm.util;
  2. import org.apache.poi.hssf.usermodel.*;
  3. import org.apache.poi.ss.usermodel.*;
  4. import org.apache.poi.ss.util.CellRangeAddress;
  5. import org.apache.poi.xssf.usermodel.XSSFWorkbook;
  6. import java.io.IOException;
  7. import java.io.InputStream;
  8. import java.io.OutputStream;
  9. import java.text.SimpleDateFormat;
  10. import java.util.ArrayList;
  11. import java.util.Date;
  12. import java.util.List;
  13. public class ExcelUtil {
  14. public static void createExcel(List<String> header, List<String[]> data, OutputStream out) throws IOException {
  15. // 创建一个Excel文件
  16. HSSFWorkbook workbook = new HSSFWorkbook();
  17. // 创建一个工作表
  18. HSSFSheet sheet = workbook.createSheet("sheet1");
  19. // 添加表头行
  20. HSSFRow hssfRow = sheet.createRow(0);
  21. // 设置单元格格式居中
  22. HSSFCellStyle cellStyle = workbook.createCellStyle();
  23. cellStyle.setAlignment(HorizontalAlignment.CENTER);
  24. // 添加表头内容
  25. for (int i = 0; i < header.size(); i++) {
  26. HSSFCell headCell = hssfRow.createCell(i);
  27. headCell.setCellValue(header.get(i));
  28. headCell.setCellStyle(cellStyle);
  29. }
  30. // 添加数据内容
  31. for (int i = 0; i < data.size(); i++) {
  32. String[] strings = data.get(i);
  33. hssfRow = sheet.createRow(i + 1);
  34. for (int j = 0; j < strings.length; j++) {
  35. HSSFCell cell = hssfRow.createCell(j);
  36. cell.setCellValue(strings[j]);
  37. cell.setCellStyle(cellStyle);
  38. }
  39. }
  40. //单元格自适应
  41. sheet.autoSizeColumn(2,true);
  42. // 保存Excel文件
  43. workbook.write(out);
  44. }
  45. public static void createExcel(String title,List<String> header, List<String[]> data, OutputStream out) throws IOException {
  46. // 创建一个Excel文件
  47. HSSFWorkbook workbook = new HSSFWorkbook();
  48. // 创建一个工作表
  49. HSSFSheet sheet = workbook.createSheet("sheet1");
  50. // 添加表头行
  51. HSSFRow hssfRow = sheet.createRow(0);
  52. HSSFCell cellTitle = hssfRow.createCell(0);
  53. // 设置标题外的单元格格式居中
  54. HSSFCellStyle cellStyle = workbook.createCellStyle();
  55. cellStyle.setAlignment(HorizontalAlignment.CENTER);
  56. //设置标题的样式
  57. HSSFCellStyle titleCellStyle = workbook.createCellStyle();
  58. titleCellStyle.setAlignment(HorizontalAlignment.CENTER);
  59. titleCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
  60. //设置标题字体的样式
  61. HSSFFont font = workbook.createFont();
  62. font.setFontHeightInPoints((short) 12);//设置字体大小
  63. titleCellStyle.setFont(font);
  64. //标题设置(四个参数分别表示起始行,终止行,起始列,终止列)
  65. cellTitle.setCellValue(title);
  66. int lastCol = header.size() > 1 ? header.size() : 2;
  67. CellRangeAddress region1 = new CellRangeAddress(0, 1, (short) 0, (short) lastCol - 1);
  68. sheet.addMergedRegion(region1);
  69. hssfRow = sheet.createRow(1);
  70. hssfRow = sheet.createRow(2);
  71. cellTitle.setCellStyle(titleCellStyle);
  72. // 添加表头内容
  73. for (int i = 0; i < header.size(); i++) {
  74. HSSFCell headCell = hssfRow.createCell(i);
  75. headCell.setCellValue(header.get(i));
  76. headCell.setCellStyle(cellStyle);
  77. }
  78. // 添加数据内容
  79. for (int i = 0; i < data.size(); i++) {
  80. String[] strings = data.get(i);
  81. hssfRow = sheet.createRow(i + 3);
  82. for (int j = 0; j < strings.length; j++) {
  83. HSSFCell cell = hssfRow.createCell(j);
  84. cell.setCellValue(strings[j]);
  85. cell.setCellStyle(cellStyle);
  86. }
  87. }
  88. // 保存Excel文件
  89. workbook.write(out);
  90. }
  91. /**
  92. * 读取Excel的内容
  93. *
  94. * @param fileType 文件类型,xls或xlsx
  95. * @param startRows 开始读取行数,比喻行头不需要读入 忽略的行数为1
  96. * @param ignoreRowBlank 是否忽略空行
  97. * @param is 文件输入流
  98. * @return 读出的Excel中数据的内容
  99. * @throws IOException duxxxxx
  100. */
  101. public static List<String[]> readData(String fileType, int startRows, boolean ignoreRowBlank, InputStream is) throws IOException {
  102. List<String[]> result = new ArrayList<>();
  103. Workbook wb = readExcel(fileType, is);
  104. for (int sheetIndex = 0; sheetIndex < wb.getNumberOfSheets(); sheetIndex++) {
  105. Sheet sheet = wb.getSheetAt(sheetIndex);
  106. for (int rowIndex = startRows, z = sheet.getLastRowNum(); rowIndex <= z; rowIndex++) {
  107. Row row = sheet.getRow(rowIndex);
  108. if (row == null) {
  109. continue;
  110. }
  111. int rowSize = sheet.getRow(0).getLastCellNum();
  112. String[] values = new String[rowSize];
  113. boolean hasValue = false;
  114. for (int columnIndex = 0; columnIndex < rowSize; columnIndex++) {
  115. String value = "";
  116. Cell cell = row.getCell(columnIndex);
  117. if (cell != null) {
  118. // 注意:一定要设成这个,否则可能会出现乱码,后面版本默认设置
  119. switch (cell.getCellType()) {
  120. case STRING:
  121. value = cell.getStringCellValue();
  122. break;
  123. case NUMERIC:
  124. if (HSSFDateUtil.isCellDateFormatted(cell)) {
  125. Date date = cell.getDateCellValue();
  126. if (date != null) {
  127. value = new SimpleDateFormat("yyyy-MM-dd")
  128. .format(date);
  129. } else {
  130. value = "";
  131. }
  132. } else {
  133. //value = new DecimalFormat("0").format(cell.getNumericCellValue());
  134. if (HSSFDateUtil.isCellDateFormatted(cell)) {
  135. value = String.valueOf(cell.getDateCellValue());
  136. } else {
  137. // cell.setCellType(Cell.CELL_TYPE_STRING);
  138. String temp = cell.getStringCellValue();
  139. // 判断是否包含小数点,如果不含小数点,则以字符串读取,如果含小数点,则转换为Double类型的字符串
  140. if (temp.indexOf(".") > -1) {
  141. value = String.valueOf(new Double(temp)).trim();
  142. } else {
  143. value = temp.trim();
  144. }
  145. }
  146. }
  147. break;
  148. case FORMULA:
  149. // 导入时如果为公式生成的数据则无值
  150. if (!cell.getStringCellValue().equals("")) {
  151. value = cell.getStringCellValue();
  152. } else {
  153. value = cell.getNumericCellValue() + "";
  154. }
  155. break;
  156. case BLANK:
  157. break;
  158. case ERROR:
  159. value = "";
  160. break;
  161. case BOOLEAN:
  162. value = (cell.getBooleanCellValue() == true ? "Y"
  163. : "N");
  164. break;
  165. default:
  166. value = "";
  167. }
  168. }
  169. values[columnIndex] = value;
  170. if (!value.isEmpty()) {
  171. hasValue = true;
  172. }
  173. }
  174. if (!ignoreRowBlank || hasValue) {//不为忽略空行模式或不为空行
  175. result.add(values);
  176. }
  177. }
  178. }
  179. return result;
  180. }
  181. //读取excel
  182. private static Workbook readExcel(String fileType, InputStream is) throws IOException {
  183. if ("xls".equals(fileType)) {
  184. return new HSSFWorkbook(is);
  185. } else if ("xlsx".equals(fileType)) {
  186. return new XSSFWorkbook(is);
  187. } else {
  188. throw new IllegalArgumentException("不支持的文件类型,仅支持xls和xlsx");
  189. }
  190. }
  191. /**
  192. * 去掉字符串右边的空格
  193. *
  194. * @param str 要处理的字符串
  195. * @return 处理后的字符串
  196. */
  197. private static String rightTrim(String str) {
  198. if (str == null) {
  199. return "";
  200. }
  201. int length = str.length();
  202. for (int i = length - 1; i >= 0; i--) {
  203. if (str.charAt(i) != 0x20) {
  204. break;
  205. }
  206. length--;
  207. }
  208. return str.substring(0, length);
  209. }
  210. }