ExcelUtils.java 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. package com.ruoyi.common.utils.file;
  2. import com.ruoyi.common.constant.Constants;
  3. import com.ruoyi.common.utils.StringUtils;
  4. import com.ruoyi.framework.config.RuoYiConfig;
  5. import com.ruoyi.framework.web.controller.BaseController;
  6. import org.apache.commons.lang.time.DateFormatUtils;
  7. import org.apache.poi.hssf.usermodel.HSSFDataFormat;
  8. import org.apache.poi.hssf.usermodel.HSSFDateUtil;
  9. import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  10. import org.apache.poi.ss.usermodel.*;
  11. import org.apache.poi.ss.util.CellRangeAddress;
  12. import org.apache.poi.util.IOUtils;
  13. import org.apache.poi.xssf.usermodel.XSSFRow;
  14. import org.apache.poi.xssf.usermodel.XSSFSheet;
  15. import org.apache.poi.xssf.usermodel.XSSFWorkbook;
  16. import org.slf4j.Logger;
  17. import org.slf4j.LoggerFactory;
  18. import org.springframework.web.multipart.MultipartFile;
  19. import java.io.*;
  20. import java.math.BigDecimal;
  21. import java.text.DecimalFormat;
  22. import java.text.NumberFormat;
  23. import java.text.SimpleDateFormat;
  24. import java.util.ArrayList;
  25. import java.util.Date;
  26. import java.util.List;
  27. /**
  28. * Created by Administrator on 2018/7/26 0026.
  29. */
  30. public class ExcelUtils {
  31. protected static final Logger logger = LoggerFactory.getLogger(BaseController.class);
  32. public static Workbook getWorkBook(MultipartFile file) {
  33. //获得文件名
  34. String fileName = file.getOriginalFilename();
  35. //创建Workbook工作薄对象,表示整个excel
  36. Workbook workbook = null;
  37. try {
  38. //获取excel文件的io流
  39. InputStream is = file.getInputStream();
  40. //根据文件后缀名不同(xls和xlsx)获得不同的Workbook实现类对象
  41. if (fileName.endsWith("xls")) {
  42. //2003
  43. workbook = new HSSFWorkbook(is);
  44. } else if (fileName.endsWith("xlsx") || fileName.endsWith("xlsm")) {
  45. //2007 及2007以上
  46. workbook = new XSSFWorkbook(is);
  47. }
  48. } catch (IOException e) {
  49. // log.error(e.getMessage());
  50. }
  51. return workbook;
  52. }
  53. public static Workbook getWorkBook(File file) {
  54. //获得文件名
  55. String fileName = file.getName();
  56. //创建Workbook工作薄对象,表示整个excel
  57. Workbook workbook = null;
  58. try {
  59. //获取excel文件的io流
  60. InputStream is = new FileInputStream(file);
  61. //根据文件后缀名不同(xls和xlsx)获得不同的Workbook实现类对象
  62. if (fileName.endsWith("xls")) {
  63. //2003
  64. workbook = new HSSFWorkbook(is);
  65. } else if (fileName.endsWith("xlsx")) {
  66. //2007 及2007以上
  67. workbook = new XSSFWorkbook(is);
  68. }
  69. } catch (IOException e) {
  70. // log.error(e.getMessage());
  71. }
  72. return workbook;
  73. }
  74. public static String getCellValue(Cell cell) {
  75. String cellValue = "";
  76. if (cell == null) {
  77. return cellValue;
  78. }
  79. logger.info("Excel格式:" + cell.getCellType().name());
  80. switch (cell.getCellType().name()) {
  81. case "STRING":
  82. cellValue = cell.getRichStringCellValue().getString();
  83. break;
  84. case "NUMERIC":
  85. logger.info("Excel数据样式:" + cell.getCellStyle().getDataFormatString());
  86. if ("General".equals(cell.getCellStyle().getDataFormatString())) {
  87. cellValue = new BigDecimal(cell.getNumericCellValue()).toPlainString();
  88. } else if ("m/d/yyyy;@".equals(cell.getCellStyle().getDataFormatString())) {
  89. cellValue = new SimpleDateFormat("yyyy-MM-dd").format(cell.getDateCellValue());
  90. } else if ("@".equals(cell.getCellStyle().getDataFormatString())) {
  91. cellValue = cell.getNumericCellValue() + "";
  92. } else if (cell.getCellStyle().getDataFormatString().indexOf("0_") > -1) {
  93. //数字非日期
  94. logger.info("Excel值:" + cell.getNumericCellValue());
  95. cellValue = cell.getNumericCellValue() + "";
  96. } else if (cell.getCellStyle().getDataFormatString().indexOf("0.0") > -1) {
  97. //数字非日期
  98. logger.info("Excel值:" + cell.getNumericCellValue());
  99. cellValue = cell.getNumericCellValue() + "";
  100. } else {
  101. try {
  102. cellValue = new SimpleDateFormat("yyyy-MM-dd").format(cell.getDateCellValue());
  103. } catch (Exception e) {
  104. cellValue = cell.getNumericCellValue() + "";
  105. }
  106. }
  107. break;
  108. case "BLANK":
  109. cellValue = "";
  110. break;
  111. default:
  112. cellValue = cell.toString();
  113. break;
  114. }
  115. //判断数据的类型
  116. // switch (cell.getCellType()) {
  117. // case Cell.CELL_TYPE_NUMERIC: //数字
  118. // cellValue = stringDateProcess(cell);
  119. // break;
  120. // case Cell.CELL_TYPE_STRING: //字符串
  121. // cellValue = String.valueOf(cell.getStringCellValue());
  122. // break;
  123. // case Cell.CELL_TYPE_BOOLEAN: //Boolean
  124. // cellValue = String.valueOf(cell.getBooleanCellValue());
  125. // break;
  126. // case Cell.CELL_TYPE_FORMULA: //公式
  127. // cellValue = String.valueOf(cell.getCellFormula());
  128. // break;
  129. // case Cell.CELL_TYPE_BLANK: //空值
  130. // cellValue = "";
  131. // break;
  132. // case Cell.CELL_TYPE_ERROR: //故障
  133. // cellValue = "非法字符";
  134. // break;
  135. // default:
  136. // cellValue = "未知类型";
  137. // break;
  138. // }
  139. // cellValue = String.valueOf(cell.getStringCellValue());
  140. return cellValue;
  141. }
  142. /**
  143. * 时间格式处理
  144. *
  145. * @return
  146. * @author Liu Xin Nan
  147. * @data 2017年11月27日
  148. */
  149. public static String stringDateProcess(Cell cell) {
  150. String result = new String();
  151. if (HSSFDateUtil.isCellDateFormatted(cell)) {// 处理日期格式、时间格式
  152. SimpleDateFormat sdf = null;
  153. if (cell.getCellStyle().getDataFormat() == HSSFDataFormat.getBuiltinFormat("h:mm")) {
  154. sdf = new SimpleDateFormat("HH:mm");
  155. } else {// 日期
  156. sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
  157. }
  158. Date date = cell.getDateCellValue();
  159. result = sdf.format(date);
  160. } else if (cell.getCellStyle().getDataFormat() == 58) {
  161. // 处理自定义日期格式:m月d日(通过判断单元格的格式id解决,id的值是58)
  162. SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
  163. double value = cell.getNumericCellValue();
  164. Date date = DateUtil
  165. .getJavaDate(value);
  166. result = sdf.format(date);
  167. } else {
  168. double value = cell.getNumericCellValue();
  169. CellStyle style = cell.getCellStyle();
  170. DecimalFormat format = new DecimalFormat();
  171. String temp = style.getDataFormatString();
  172. // 单元格设置成常规
  173. if (temp.equals("General")) {
  174. format.applyPattern("#");
  175. }
  176. result = format.format(value);
  177. }
  178. return result;
  179. }
  180. /**
  181. * 合并单元格处理,获取合并行
  182. *
  183. * @param sheet
  184. * @return List<CellRangeAddress>
  185. */
  186. public static List<CellRangeAddress> getCombineCell(Sheet sheet) {
  187. List<CellRangeAddress> list = new ArrayList<CellRangeAddress>();
  188. //获得一个 sheet 中合并单元格的数量
  189. int sheetmergerCount = sheet.getNumMergedRegions();
  190. //遍历所有的合并单元格
  191. for (int i = 0; i < sheetmergerCount; i++) {
  192. //获得合并单元格保存进list中
  193. CellRangeAddress ca = sheet.getMergedRegion(i);
  194. list.add(ca);
  195. }
  196. return list;
  197. }
  198. public static int getRowNum(List<CellRangeAddress> listCombineCell, Cell cell, Sheet sheet) {
  199. int xr = 0;
  200. int firstC = 0;
  201. int lastC = 0;
  202. int firstR = 0;
  203. int lastR = 0;
  204. for (CellRangeAddress ca : listCombineCell) {
  205. //获得合并单元格的起始行, 结束行, 起始列, 结束列
  206. firstC = ca.getFirstColumn();
  207. lastC = ca.getLastColumn();
  208. firstR = ca.getFirstRow();
  209. lastR = ca.getLastRow();
  210. if (cell.getRowIndex() >= firstR && cell.getRowIndex() <= lastR) {
  211. if (cell.getColumnIndex() >= firstC && cell.getColumnIndex() <= lastC) {
  212. xr = lastR;
  213. }
  214. }
  215. }
  216. return xr;
  217. }
  218. /**
  219. * 判断单元格是否为合并单元格,是的话则将单元格的值返回
  220. *
  221. * @param listCombineCell 存放合并单元格的list
  222. * @param cell 需要判断的单元格
  223. * @param sheet sheet
  224. * @return
  225. */
  226. public static String isCombineCell(List<CellRangeAddress> listCombineCell, Cell cell, Sheet sheet)
  227. throws Exception {
  228. int firstC = 0;
  229. int lastC = 0;
  230. int firstR = 0;
  231. int lastR = 0;
  232. String cellValue = null;
  233. for (CellRangeAddress ca : listCombineCell) {
  234. //获得合并单元格的起始行, 结束行, 起始列, 结束列
  235. firstC = ca.getFirstColumn();
  236. lastC = ca.getLastColumn();
  237. firstR = ca.getFirstRow();
  238. lastR = ca.getLastRow();
  239. if (cell.getRowIndex() >= firstR && cell.getRowIndex() <= lastR) {
  240. if (cell.getColumnIndex() >= firstC && cell.getColumnIndex() <= lastC) {
  241. Row fRow = sheet.getRow(firstR);
  242. Cell fCell = fRow.getCell(firstC);
  243. cellValue = getCellValue(fCell);
  244. break;
  245. }
  246. } else {
  247. cellValue = "";
  248. }
  249. }
  250. return cellValue;
  251. }
  252. /**
  253. * 获取合并单元格的值
  254. *
  255. * @param sheet
  256. * @param row
  257. * @param column
  258. * @return
  259. */
  260. public static String getMergedRegionValue(Sheet sheet, int row, int column) {
  261. int sheetMergeCount = sheet.getNumMergedRegions();
  262. for (int i = 0; i < sheetMergeCount; i++) {
  263. CellRangeAddress ca = sheet.getMergedRegion(i);
  264. int firstColumn = ca.getFirstColumn();
  265. int lastColumn = ca.getLastColumn();
  266. int firstRow = ca.getFirstRow();
  267. int lastRow = ca.getLastRow();
  268. if (row >= firstRow && row <= lastRow) {
  269. if (column >= firstColumn && column <= lastColumn) {
  270. Row fRow = sheet.getRow(firstRow);
  271. Cell fCell = fRow.getCell(firstColumn);
  272. return getCellValue(fCell);
  273. }
  274. }
  275. }
  276. return null;
  277. }
  278. /**
  279. * 判断指定的单元格是否是合并单元格
  280. *
  281. * @param sheet
  282. * @param row 行下标
  283. * @param column 列下标
  284. * @return
  285. */
  286. public static boolean isMergedRegion(Sheet sheet, int row, int column) {
  287. int sheetMergeCount = sheet.getNumMergedRegions();
  288. for (int i = 0; i < sheetMergeCount; i++) {
  289. CellRangeAddress range = sheet.getMergedRegion(i);
  290. int firstColumn = range.getFirstColumn();
  291. int lastColumn = range.getLastColumn();
  292. int firstRow = range.getFirstRow();
  293. int lastRow = range.getLastRow();
  294. if (row >= firstRow && row <= lastRow) {
  295. if (column >= firstColumn && column <= lastColumn) {
  296. return true;
  297. }
  298. }
  299. }
  300. return false;
  301. }
  302. public static void insertPicture(XSSFWorkbook workbook, XSSFSheet sheet, String fileUrl, int row, int col, double scaleX, double scaleY) {
  303. try {
  304. // 输入流
  305. String localPath = RuoYiConfig.getProfile();
  306. String imagePath = localPath + StringUtils.substringAfter(fileUrl, Constants.RESOURCE_PREFIX);
  307. InputStream is = new FileInputStream(imagePath);
  308. byte[] bytes = IOUtils.toByteArray(is);
  309. @SuppressWarnings("static-access")
  310. int pictureIdx = workbook.addPicture(bytes, workbook.PICTURE_TYPE_PNG);
  311. CreationHelper helper = workbook.getCreationHelper();
  312. Drawing drawing = sheet.createDrawingPatriarch();
  313. ClientAnchor anchor = helper.createClientAnchor();
  314. // 图片插入坐标
  315. anchor.setCol1(col);
  316. anchor.setRow1(row);
  317. anchor.setCol2(col+1);
  318. anchor.setRow2(row+1);
  319. anchor.setDx1(100000);
  320. anchor.setDy1(50000);
  321. // 插入图片
  322. Picture pict = drawing.createPicture(anchor, pictureIdx);
  323. pict.resize(scaleX, scaleY);
  324. is.close();
  325. } catch (FileNotFoundException e) {
  326. // e.printStackTrace();
  327. } catch (IOException e) {
  328. // e.printStackTrace();
  329. }
  330. }
  331. public static void createVoidCell(int startCell, int endCell, XSSFRow row) {
  332. for (int i = startCell; i <= endCell; i++) {
  333. row.createCell(i);
  334. }
  335. }
  336. }