123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358 |
- package com.ruoyi.common.utils.file;
- import com.ruoyi.common.constant.Constants;
- import com.ruoyi.common.utils.StringUtils;
- import com.ruoyi.framework.config.RuoYiConfig;
- import com.ruoyi.framework.web.controller.BaseController;
- import org.apache.commons.lang.time.DateFormatUtils;
- import org.apache.poi.hssf.usermodel.HSSFDataFormat;
- import org.apache.poi.hssf.usermodel.HSSFDateUtil;
- import org.apache.poi.hssf.usermodel.HSSFWorkbook;
- import org.apache.poi.ss.usermodel.*;
- import org.apache.poi.ss.util.CellRangeAddress;
- import org.apache.poi.util.IOUtils;
- import org.apache.poi.xssf.usermodel.XSSFRow;
- import org.apache.poi.xssf.usermodel.XSSFSheet;
- import org.apache.poi.xssf.usermodel.XSSFWorkbook;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- import org.springframework.web.multipart.MultipartFile;
- import java.io.*;
- import java.math.BigDecimal;
- import java.text.DecimalFormat;
- import java.text.NumberFormat;
- import java.text.SimpleDateFormat;
- import java.util.ArrayList;
- import java.util.Date;
- import java.util.List;
- /**
- * Created by Administrator on 2018/7/26 0026.
- */
- public class ExcelUtils {
- protected static final Logger logger = LoggerFactory.getLogger(BaseController.class);
- public static Workbook getWorkBook(MultipartFile file) {
- //获得文件名
- String fileName = file.getOriginalFilename();
- //创建Workbook工作薄对象,表示整个excel
- Workbook workbook = null;
- try {
- //获取excel文件的io流
- InputStream is = file.getInputStream();
- //根据文件后缀名不同(xls和xlsx)获得不同的Workbook实现类对象
- if (fileName.endsWith("xls")) {
- //2003
- workbook = new HSSFWorkbook(is);
- } else if (fileName.endsWith("xlsx") || fileName.endsWith("xlsm")) {
- //2007 及2007以上
- workbook = new XSSFWorkbook(is);
- }
- } catch (IOException e) {
- // log.error(e.getMessage());
- }
- return workbook;
- }
- public static Workbook getWorkBook(File file) {
- //获得文件名
- String fileName = file.getName();
- //创建Workbook工作薄对象,表示整个excel
- Workbook workbook = null;
- try {
- //获取excel文件的io流
- InputStream is = new FileInputStream(file);
- //根据文件后缀名不同(xls和xlsx)获得不同的Workbook实现类对象
- if (fileName.endsWith("xls")) {
- //2003
- workbook = new HSSFWorkbook(is);
- } else if (fileName.endsWith("xlsx")) {
- //2007 及2007以上
- workbook = new XSSFWorkbook(is);
- }
- } catch (IOException e) {
- // log.error(e.getMessage());
- }
- return workbook;
- }
- public static String getCellValue(Cell cell) {
- String cellValue = "";
- if (cell == null) {
- return cellValue;
- }
- logger.info("Excel格式:" + cell.getCellType().name());
- switch (cell.getCellType().name()) {
- case "STRING":
- cellValue = cell.getRichStringCellValue().getString();
- break;
- case "NUMERIC":
- logger.info("Excel数据样式:" + cell.getCellStyle().getDataFormatString());
- if ("General".equals(cell.getCellStyle().getDataFormatString())) {
- cellValue = new BigDecimal(cell.getNumericCellValue()).toPlainString();
- } else if ("m/d/yyyy;@".equals(cell.getCellStyle().getDataFormatString())) {
- cellValue = new SimpleDateFormat("yyyy-MM-dd").format(cell.getDateCellValue());
- } else if ("@".equals(cell.getCellStyle().getDataFormatString())) {
- cellValue = cell.getNumericCellValue() + "";
- } else if (cell.getCellStyle().getDataFormatString().indexOf("0_") > -1) {
- //数字非日期
- logger.info("Excel值:" + cell.getNumericCellValue());
- cellValue = cell.getNumericCellValue() + "";
- } else if (cell.getCellStyle().getDataFormatString().indexOf("0.0") > -1) {
- //数字非日期
- logger.info("Excel值:" + cell.getNumericCellValue());
- cellValue = cell.getNumericCellValue() + "";
- } else {
- try {
- cellValue = new SimpleDateFormat("yyyy-MM-dd").format(cell.getDateCellValue());
- } catch (Exception e) {
- cellValue = cell.getNumericCellValue() + "";
- }
- }
- break;
- case "BLANK":
- cellValue = "";
- break;
- default:
- cellValue = cell.toString();
- break;
- }
- //判断数据的类型
- // switch (cell.getCellType()) {
- // case Cell.CELL_TYPE_NUMERIC: //数字
- // cellValue = stringDateProcess(cell);
- // break;
- // case Cell.CELL_TYPE_STRING: //字符串
- // cellValue = String.valueOf(cell.getStringCellValue());
- // break;
- // case Cell.CELL_TYPE_BOOLEAN: //Boolean
- // cellValue = String.valueOf(cell.getBooleanCellValue());
- // break;
- // case Cell.CELL_TYPE_FORMULA: //公式
- // cellValue = String.valueOf(cell.getCellFormula());
- // break;
- // case Cell.CELL_TYPE_BLANK: //空值
- // cellValue = "";
- // break;
- // case Cell.CELL_TYPE_ERROR: //故障
- // cellValue = "非法字符";
- // break;
- // default:
- // cellValue = "未知类型";
- // break;
- // }
- // cellValue = String.valueOf(cell.getStringCellValue());
- return cellValue;
- }
- /**
- * 时间格式处理
- *
- * @return
- * @author Liu Xin Nan
- * @data 2017年11月27日
- */
- public static String stringDateProcess(Cell cell) {
- String result = new String();
- if (HSSFDateUtil.isCellDateFormatted(cell)) {// 处理日期格式、时间格式
- SimpleDateFormat sdf = null;
- if (cell.getCellStyle().getDataFormat() == HSSFDataFormat.getBuiltinFormat("h:mm")) {
- sdf = new SimpleDateFormat("HH:mm");
- } else {// 日期
- sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
- }
- Date date = cell.getDateCellValue();
- result = sdf.format(date);
- } else if (cell.getCellStyle().getDataFormat() == 58) {
- // 处理自定义日期格式:m月d日(通过判断单元格的格式id解决,id的值是58)
- SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
- double value = cell.getNumericCellValue();
- Date date = DateUtil
- .getJavaDate(value);
- result = sdf.format(date);
- } else {
- double value = cell.getNumericCellValue();
- CellStyle style = cell.getCellStyle();
- DecimalFormat format = new DecimalFormat();
- String temp = style.getDataFormatString();
- // 单元格设置成常规
- if (temp.equals("General")) {
- format.applyPattern("#");
- }
- result = format.format(value);
- }
- return result;
- }
- /**
- * 合并单元格处理,获取合并行
- *
- * @param sheet
- * @return List<CellRangeAddress>
- */
- public static List<CellRangeAddress> getCombineCell(Sheet sheet) {
- List<CellRangeAddress> list = new ArrayList<CellRangeAddress>();
- //获得一个 sheet 中合并单元格的数量
- int sheetmergerCount = sheet.getNumMergedRegions();
- //遍历所有的合并单元格
- for (int i = 0; i < sheetmergerCount; i++) {
- //获得合并单元格保存进list中
- CellRangeAddress ca = sheet.getMergedRegion(i);
- list.add(ca);
- }
- return list;
- }
- public static int getRowNum(List<CellRangeAddress> listCombineCell, Cell cell, Sheet sheet) {
- int xr = 0;
- int firstC = 0;
- int lastC = 0;
- int firstR = 0;
- int lastR = 0;
- for (CellRangeAddress ca : listCombineCell) {
- //获得合并单元格的起始行, 结束行, 起始列, 结束列
- firstC = ca.getFirstColumn();
- lastC = ca.getLastColumn();
- firstR = ca.getFirstRow();
- lastR = ca.getLastRow();
- if (cell.getRowIndex() >= firstR && cell.getRowIndex() <= lastR) {
- if (cell.getColumnIndex() >= firstC && cell.getColumnIndex() <= lastC) {
- xr = lastR;
- }
- }
- }
- return xr;
- }
- /**
- * 判断单元格是否为合并单元格,是的话则将单元格的值返回
- *
- * @param listCombineCell 存放合并单元格的list
- * @param cell 需要判断的单元格
- * @param sheet sheet
- * @return
- */
- public static String isCombineCell(List<CellRangeAddress> listCombineCell, Cell cell, Sheet sheet)
- throws Exception {
- int firstC = 0;
- int lastC = 0;
- int firstR = 0;
- int lastR = 0;
- String cellValue = null;
- for (CellRangeAddress ca : listCombineCell) {
- //获得合并单元格的起始行, 结束行, 起始列, 结束列
- firstC = ca.getFirstColumn();
- lastC = ca.getLastColumn();
- firstR = ca.getFirstRow();
- lastR = ca.getLastRow();
- if (cell.getRowIndex() >= firstR && cell.getRowIndex() <= lastR) {
- if (cell.getColumnIndex() >= firstC && cell.getColumnIndex() <= lastC) {
- Row fRow = sheet.getRow(firstR);
- Cell fCell = fRow.getCell(firstC);
- cellValue = getCellValue(fCell);
- break;
- }
- } else {
- cellValue = "";
- }
- }
- return cellValue;
- }
- /**
- * 获取合并单元格的值
- *
- * @param sheet
- * @param row
- * @param column
- * @return
- */
- public static String getMergedRegionValue(Sheet sheet, int row, int column) {
- int sheetMergeCount = sheet.getNumMergedRegions();
- for (int i = 0; i < sheetMergeCount; i++) {
- CellRangeAddress ca = sheet.getMergedRegion(i);
- int firstColumn = ca.getFirstColumn();
- int lastColumn = ca.getLastColumn();
- int firstRow = ca.getFirstRow();
- int lastRow = ca.getLastRow();
- if (row >= firstRow && row <= lastRow) {
- if (column >= firstColumn && column <= lastColumn) {
- Row fRow = sheet.getRow(firstRow);
- Cell fCell = fRow.getCell(firstColumn);
- return getCellValue(fCell);
- }
- }
- }
- return null;
- }
- /**
- * 判断指定的单元格是否是合并单元格
- *
- * @param sheet
- * @param row 行下标
- * @param column 列下标
- * @return
- */
- public static boolean isMergedRegion(Sheet sheet, int row, int column) {
- int sheetMergeCount = sheet.getNumMergedRegions();
- for (int i = 0; i < sheetMergeCount; i++) {
- CellRangeAddress range = sheet.getMergedRegion(i);
- int firstColumn = range.getFirstColumn();
- int lastColumn = range.getLastColumn();
- int firstRow = range.getFirstRow();
- int lastRow = range.getLastRow();
- if (row >= firstRow && row <= lastRow) {
- if (column >= firstColumn && column <= lastColumn) {
- return true;
- }
- }
- }
- return false;
- }
- public static void insertPicture(XSSFWorkbook workbook, XSSFSheet sheet, String fileUrl, int row, int col, double scaleX, double scaleY) {
- try {
- // 输入流
- String localPath = RuoYiConfig.getProfile();
- String imagePath = localPath + StringUtils.substringAfter(fileUrl, Constants.RESOURCE_PREFIX);
- InputStream is = new FileInputStream(imagePath);
- byte[] bytes = IOUtils.toByteArray(is);
- @SuppressWarnings("static-access")
- int pictureIdx = workbook.addPicture(bytes, workbook.PICTURE_TYPE_PNG);
- CreationHelper helper = workbook.getCreationHelper();
- Drawing drawing = sheet.createDrawingPatriarch();
- ClientAnchor anchor = helper.createClientAnchor();
- // 图片插入坐标
- anchor.setCol1(col);
- anchor.setRow1(row);
- anchor.setCol2(col+1);
- anchor.setRow2(row+1);
- anchor.setDx1(100000);
- anchor.setDy1(50000);
- // 插入图片
- Picture pict = drawing.createPicture(anchor, pictureIdx);
- pict.resize(scaleX, scaleY);
- is.close();
- } catch (FileNotFoundException e) {
- // e.printStackTrace();
- } catch (IOException e) {
- // e.printStackTrace();
- }
- }
- public static void createVoidCell(int startCell, int endCell, XSSFRow row) {
- for (int i = startCell; i <= endCell; i++) {
- row.createCell(i);
- }
- }
- }
|