anderx 3 anni fa
parent
commit
2fd128dc53

+ 17 - 8
src/main/java/com/goafanti/common/utils/DateUtils.java

@@ -2,6 +2,7 @@ package com.goafanti.common.utils;
 
 import java.text.ParseException;
 import java.text.SimpleDateFormat;
+import java.time.*;
 import java.util.Calendar;
 import java.util.Date;
 
@@ -23,7 +24,7 @@ public class DateUtils extends org.apache.commons.lang3.time.DateUtils {
 	/**
 	 * Determines how two dates compare up to no more than the specified most
 	 * significant field.
-	 * 
+	 *
 	 * @param date1
 	 *            the first date, not <code>null</code>
 	 * @param date2
@@ -48,7 +49,7 @@ public class DateUtils extends org.apache.commons.lang3.time.DateUtils {
 	/**
 	 * Determines how two dates compare up to no more than the specified most
 	 * significant field.
-	 * 
+	 *
 	 * @param date1
 	 *            the first date, not <code>null</code>
 	 * @param date2
@@ -68,7 +69,7 @@ public class DateUtils extends org.apache.commons.lang3.time.DateUtils {
 	/**
 	 * Determines how two dates compare up to no more than the specified most
 	 * significant field.
-	 * 
+	 *
 	 * @param date1
 	 *            the first date, not <code>null</code>
 	 * @param date2
@@ -375,7 +376,7 @@ public class DateUtils extends org.apache.commons.lang3.time.DateUtils {
 		return calendar.getTime();
 	}
 
-	/** 
+	/**
 	 *  返回前一年最后一天
 	 * @param date
 	 * @return
@@ -414,7 +415,7 @@ public class DateUtils extends org.apache.commons.lang3.time.DateUtils {
 	 * @param source
 	 * @param pattern
 	 * @return
-	 * @throws ParseException 
+	 * @throws ParseException
 	 */
 	public static Date parseDate(String source, String pattern) throws ParseException {
 		SimpleDateFormat format = new SimpleDateFormat(pattern);
@@ -443,7 +444,7 @@ public class DateUtils extends org.apache.commons.lang3.time.DateUtils {
 		setMidnight(c);
 		return c.getTime();
 	}
-	
+
 	/**
 	 * 字符串转日期
 	 * @param date
@@ -460,12 +461,20 @@ public class DateUtils extends org.apache.commons.lang3.time.DateUtils {
 		}
 		return date2;
 	}
-	
+
 
 	public static final String parseDateToStr(final String format, final Date date) {
         return new SimpleDateFormat(format).format(date);
     }
 
 
-	
+	/**
+	 * 增加 LocalDate ==> Date
+	 */
+	public static Date toDate(LocalDate temporalAccessor)
+	{
+		LocalDateTime localDateTime = LocalDateTime.of(temporalAccessor, LocalTime.of(0, 0, 0));
+		ZonedDateTime zdt = localDateTime.atZone(ZoneId.systemDefault());
+		return Date.from(zdt.toInstant());
+	}
 }

+ 88 - 0
src/main/java/com/goafanti/common/utils/excel/CharsetKit.java

@@ -0,0 +1,88 @@
+package com.goafanti.common.utils.excel;
+
+
+import com.goafanti.common.utils.StringUtils;
+
+import java.nio.charset.Charset;
+import java.nio.charset.StandardCharsets;
+
+/**
+ * 字符集工具类
+ *
+ * @author ruoyi
+ */
+public class CharsetKit
+{
+    /** ISO-8859-1 */
+    public static final String ISO_8859_1 = "ISO-8859-1";
+    /** UTF-8 */
+    public static final String UTF_8 = "UTF-8";
+    /** GBK */
+    public static final String GBK = "GBK";
+
+    /** ISO-8859-1 */
+    public static final Charset CHARSET_ISO_8859_1 = Charset.forName(ISO_8859_1);
+    /** UTF-8 */
+    public static final Charset CHARSET_UTF_8 = Charset.forName(UTF_8);
+    /** GBK */
+    public static final Charset CHARSET_GBK = Charset.forName(GBK);
+
+    /**
+     * 转换为Charset对象
+     *
+     * @param charset 字符集,为空则返回默认字符集
+     * @return Charset
+     */
+    public static Charset charset(String charset)
+    {
+        return StringUtils.isEmpty(charset) ? Charset.defaultCharset() : Charset.forName(charset);
+    }
+
+    /**
+     * 转换字符串的字符集编码
+     *
+     * @param source 字符串
+     * @param srcCharset 源字符集,默认ISO-8859-1
+     * @param destCharset 目标字符集,默认UTF-8
+     * @return 转换后的字符集
+     */
+    public static String convert(String source, String srcCharset, String destCharset)
+    {
+        return convert(source, Charset.forName(srcCharset), Charset.forName(destCharset));
+    }
+
+    /**
+     * 转换字符串的字符集编码
+     *
+     * @param source 字符串
+     * @param srcCharset 源字符集,默认ISO-8859-1
+     * @param destCharset 目标字符集,默认UTF-8
+     * @return 转换后的字符集
+     */
+    public static String convert(String source, Charset srcCharset, Charset destCharset)
+    {
+        if (null == srcCharset)
+        {
+            srcCharset = StandardCharsets.ISO_8859_1;
+        }
+
+        if (null == destCharset)
+        {
+            destCharset = StandardCharsets.UTF_8;
+        }
+
+        if (StringUtils.isEmpty(source) || srcCharset.equals(destCharset))
+        {
+            return source;
+        }
+        return new String(source.getBytes(srcCharset), destCharset);
+    }
+
+    /**
+     * @return 系统字符集编码
+     */
+    public static String systemCharset()
+    {
+        return Charset.defaultCharset().name();
+    }
+}

File diff suppressed because it is too large
+ 1002 - 0
src/main/java/com/goafanti/common/utils/excel/Convert.java


+ 408 - 22
src/main/java/com/goafanti/common/utils/excel/NewExcelUtil.java

@@ -15,36 +15,22 @@ import java.math.BigDecimal;
 import java.net.URL;
 import java.net.URLConnection;
 import java.text.DecimalFormat;
+import java.time.LocalDate;
+import java.time.LocalDateTime;
 import java.util.*;
 import java.util.stream.Collectors;
 
 import javax.servlet.http.HttpServletResponse;
 
-import org.apache.poi.ss.usermodel.BorderStyle;
-import org.apache.poi.ss.usermodel.Cell;
-import org.apache.poi.ss.usermodel.CellStyle;
-import org.apache.poi.ss.usermodel.CellType;
-import org.apache.poi.ss.usermodel.ClientAnchor;
-import org.apache.poi.ss.usermodel.DataValidation;
-import org.apache.poi.ss.usermodel.DataValidationConstraint;
-import org.apache.poi.ss.usermodel.DataValidationHelper;
-import org.apache.poi.ss.usermodel.DateUtil;
-import org.apache.poi.ss.usermodel.Drawing;
-import org.apache.poi.ss.usermodel.FillPatternType;
-import org.apache.poi.ss.usermodel.Font;
-import org.apache.poi.ss.usermodel.HorizontalAlignment;
-import org.apache.poi.ss.usermodel.IndexedColors;
-import org.apache.poi.ss.usermodel.Row;
-import org.apache.poi.ss.usermodel.Sheet;
-import org.apache.poi.ss.usermodel.VerticalAlignment;
-import org.apache.poi.ss.usermodel.Workbook;
+import org.apache.poi.POIXMLDocumentPart;
+import org.apache.poi.hssf.usermodel.*;
+import org.apache.poi.ss.usermodel.*;
 import org.apache.poi.ss.util.CellRangeAddress;
 import org.apache.poi.ss.util.CellRangeAddressList;
 import org.apache.poi.util.IOUtils;
 import org.apache.poi.xssf.streaming.SXSSFWorkbook;
-import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
-import org.apache.poi.xssf.usermodel.XSSFDataValidation;
-import org.apache.poi.xssf.usermodel.XSSFWorkbook;
+import org.apache.poi.xssf.usermodel.*;
+import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTMarker;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -82,7 +68,12 @@ public class NewExcelUtil<T> {
 	/**
 	 * 工作薄对象
 	 */
-	private XSSFWorkbook wb;
+	private Workbook wb;
+
+	/**
+	 * 导出类型(EXPORT:导出数据;IMPORT:导入模板)
+	 */
+	private Type type;
 
 	/**
 	 * 工作表对象
@@ -105,6 +96,11 @@ public class NewExcelUtil<T> {
 	private List<Object[]> fields;
 
 	/**
+	 * 标题
+	 */
+	private String title;
+
+	/**
 	 * 最大高度
 	 */
 	private short maxHeight;
@@ -137,6 +133,19 @@ public class NewExcelUtil<T> {
 		createExcelField();
 		createWorkbook();
 	}
+	public void init(List<T> list, String sheetName, String title, Type type)
+	{
+		if (list == null)
+		{
+			list = new ArrayList<T>();
+		}
+		this.list = list;
+		this.sheetName = sheetName;
+		this.type = type;
+		this.title = title;
+		createExcelField();
+		createWorkbook();
+	}
 
 	/**
 	 * 对list数据源将其里面的数据导入到excel表单
@@ -1099,8 +1108,385 @@ public class NewExcelUtil<T> {
 			IOUtils.closeQuietly(baos);
 		}
 	}
+	/**
+	 * 对excel表单默认第一个索引名转换成list
+	 *
+	 * @param is 输入流
+	 * @return 转换后集合
+	 */
+	public List<T> importExcel(InputStream is) throws Exception
+	{
+		return importExcel(is, 0);
+	}
+
+	/**
+	 * 对excel表单默认第一个索引名转换成list
+	 *
+	 * @param is 输入流
+	 * @param titleNum 标题占用行数
+	 * @return 转换后集合
+	 */
+	public List<T> importExcel(InputStream is, int titleNum) throws Exception
+	{
+		return importExcel(StringUtils.EMPTY, is, titleNum);
+	}
+
+
+	/**
+	 * 对excel表单指定表格索引名转换成list
+	 *
+	 * @param sheetName 表格索引名
+	 * @param titleNum 标题占用行数
+	 * @param is 输入流
+	 * @return 转换后集合
+	 */
+	public List<T> importExcel(String sheetName, InputStream is, int titleNum) throws Exception
+	{
+		this.type = Type.IMPORT;
+		this.wb = WorkbookFactory.create(is);
+		List<T> list = new ArrayList<T>();
+		// 如果指定sheet名,则取指定sheet中的内容 否则默认指向第1个sheet
+		Sheet sheet = StringUtils.isNotEmpty(sheetName) ? wb.getSheet(sheetName) : wb.getSheetAt(0);
+		if (sheet == null)
+		{
+			throw new IOException("文件sheet不存在");
+		}
+		boolean isXSSFWorkbook = !(wb instanceof HSSFWorkbook);
+		Map<String, PictureData> pictures;
+		if (isXSSFWorkbook)
+		{
+			pictures = getSheetPictures07((XSSFSheet) sheet, (XSSFWorkbook) wb);
+		}
+		else
+		{
+			pictures = getSheetPictures03((HSSFSheet) sheet, (HSSFWorkbook) wb);
+		}
+		// 获取最后一个非空行的行下标,比如总行数为n,则返回的为n-1
+		int rows = sheet.getLastRowNum();
+
+		if (rows > 0)
+		{
+			// 定义一个map用于存放excel列的序号和field.
+			Map<String, Integer> cellMap = new HashMap<String, Integer>();
+			// 获取表头
+			Row heard = sheet.getRow(titleNum);
+			for (int i = 0; i < heard.getPhysicalNumberOfCells(); i++)
+			{
+				Cell cell = heard.getCell(i);
+				if (StringUtils.isNotNull(cell))
+				{
+					String value = this.getCellValue(heard, i).toString();
+					cellMap.put(value, i);
+				}
+				else
+				{
+					cellMap.put(null, i);
+				}
+			}
+			// 有数据时才处理 得到类的所有field.
+			List<Object[]> fields = this.getFields();
+			Map<Integer, Object[]> fieldsMap = new HashMap<Integer, Object[]>();
+			for (Object[] objects : fields)
+			{
+				Excel attr = (Excel) objects[1];
+				Integer column = cellMap.get(attr.name());
+				if (column != null)
+				{
+					fieldsMap.put(column, objects);
+				}
+			}
+			for (int i = titleNum + 1; i <= rows; i++)
+			{
+				// 从第2行开始取数据,默认第一行是表头.
+				Row row = sheet.getRow(i);
+				// 判断当前行是否是空行
+				if (isRowEmpty(row))
+				{
+					continue;
+				}
+				T entity = null;
+				for (Map.Entry<Integer, Object[]> entry : fieldsMap.entrySet())
+				{
+					Object val = this.getCellValue(row, entry.getKey());
+
+					// 如果不存在实例则新建.
+					entity = (entity == null ? clazz.newInstance() : entity);
+					// 从map中得到对应列的field.
+					Field field = (Field) entry.getValue()[0];
+					Excel attr = (Excel) entry.getValue()[1];
+					// 取得类型,并根据对象类型设置值.
+					Class<?> fieldType = field.getType();
+					if (String.class == fieldType)
+					{
+						String s = Convert.toStr(val);
+						if (StringUtils.endsWith(s, ".0"))
+						{
+							val = StringUtils.substringBefore(s, ".0");
+						}
+						else
+						{
+							String dateFormat = field.getAnnotation(Excel.class).dateFormat();
+							if (StringUtils.isNotEmpty(dateFormat))
+							{
+								val = parseDateToStr(dateFormat, val);
+							}
+							else
+							{
+								val = Convert.toStr(val);
+							}
+						}
+					}
+					else if ((Integer.TYPE == fieldType || Integer.class == fieldType) && StringUtils.isNumeric(Convert.toStr(val)))
+					{
+						val = Convert.toInt(val);
+					}
+					else if ((Long.TYPE == fieldType || Long.class == fieldType) && StringUtils.isNumeric(Convert.toStr(val)))
+					{
+						val = Convert.toLong(val);
+					}
+					else if (Double.TYPE == fieldType || Double.class == fieldType)
+					{
+						val = Convert.toDouble(val);
+					}
+					else if (Float.TYPE == fieldType || Float.class == fieldType)
+					{
+						val = Convert.toFloat(val);
+					}
+					else if (BigDecimal.class == fieldType)
+					{
+						val = Convert.toBigDecimal(val);
+					}
+					else if (Date.class == fieldType)
+					{
+						if (val instanceof String)
+						{
+							val = DateUtils.parseDate(val);
+						}
+						else if (val instanceof Double)
+						{
+							val = DateUtil.getJavaDate((Double) val);
+						}
+					}
+					else if (Boolean.TYPE == fieldType || Boolean.class == fieldType)
+					{
+						val = Convert.toBool(val, false);
+					}
+					if (StringUtils.isNotNull(fieldType))
+					{
+						String propertyName = field.getName();
+						if (StringUtils.isNotEmpty(attr.targetAttr()))
+						{
+							propertyName = field.getName() + "." + attr.targetAttr();
+						}
+						else if (StringUtils.isNotEmpty(attr.readConverterExp()))
+						{
+							val = reverseByExp(Convert.toStr(val), attr.readConverterExp(), attr.separator());
+						}
+
+						else if (!attr.handler().equals(ExcelHandlerAdapter.class))
+						{
+							val = dataFormatHandlerAdapter(val, attr);
+						}
+						else if (ColumnType.IMAGE == attr.cellType() && StringUtils.isNotEmpty(pictures))
+						{
+							PictureData image = pictures.get(row.getRowNum() + "_" + entry.getKey());
+							if (image == null)
+							{
+								val = "";
+							}
+							else
+							{
+								byte[] data = image.getData();
+								val = FileUtils.writeImportBytes(data);
+							}
+						}
+						ReflectUtils.invokeSetter(entity, propertyName, val);
+					}
+				}
+				list.add(entity);
+			}
+		}
+		return list;
+	}
+
+	/**
+	 * 判断是否是空行
+	 *
+	 * @param row 判断的行
+	 * @return
+	 */
+	private boolean isRowEmpty(Row row)
+	{
+		if (row == null)
+		{
+			return true;
+		}
+		for (int i = row.getFirstCellNum(); i < row.getLastCellNum(); i++)
+		{
+			Cell cell = row.getCell(i);
+			if (cell != null && cell.getCellTypeEnum() != CellType.BLANK)
+			{
+				return false;
+			}
+		}
+		return true;
+	}
+
+	/**
+	 * 格式化不同类型的日期对象
+	 *
+	 * @param dateFormat 日期格式
+	 * @param val 被格式化的日期对象
+	 * @return 格式化后的日期字符
+	 */
+	public String parseDateToStr(String dateFormat, Object val)
+	{
+		if (val == null)
+		{
+			return "";
+		}
+		String str;
+		if (val instanceof Date)
+		{
+			str = DateUtils.parseDateToStr(dateFormat, (Date) val);
+		}
+		else if (val instanceof LocalDateTime)
+		{
+			str = DateUtils.parseDateToStr(dateFormat, DateUtils.toDate(LocalDate.from((LocalDateTime) val)));
+		}
+		else if (val instanceof LocalDate)
+		{
+			str = DateUtils.parseDateToStr(dateFormat, DateUtils.toDate((LocalDate) val));
+		}
+		else
+		{
+			str = val.toString();
+		}
+		return str;
+	}
+
+
 
+	public enum Type
+	{
+		ALL(0), EXPORT(1), IMPORT(2);
+		private final int value;
 
+		Type(int value)
+		{
+			this.value = value;
+		}
+
+		public int value()
+		{
+			return this.value;
+		}
+	}
+
+	/**
+	 * 获取Excel2003图片
+	 *
+	 * @param sheet 当前sheet对象
+	 * @param workbook 工作簿对象
+	 * @return Map key:图片单元格索引(1_1)String,value:图片流PictureData
+	 */
+	public static Map<String, PictureData> getSheetPictures03(HSSFSheet sheet, HSSFWorkbook workbook)
+	{
+		Map<String, PictureData> sheetIndexPicMap = new HashMap<String, PictureData>();
+		List<HSSFPictureData> pictures = workbook.getAllPictures();
+		if (!pictures.isEmpty())
+		{
+			for (HSSFShape shape : sheet.getDrawingPatriarch().getChildren())
+			{
+				HSSFClientAnchor anchor = (HSSFClientAnchor) shape.getAnchor();
+				if (shape instanceof HSSFPicture)
+				{
+					HSSFPicture pic = (HSSFPicture) shape;
+					int pictureIndex = pic.getPictureIndex() - 1;
+					HSSFPictureData picData = pictures.get(pictureIndex);
+					String picIndex = String.valueOf(anchor.getRow1()) + "_" + String.valueOf(anchor.getCol1());
+					sheetIndexPicMap.put(picIndex, picData);
+				}
+			}
+			return sheetIndexPicMap;
+		}
+		else
+		{
+			return sheetIndexPicMap;
+		}
+	}
+
+	/**
+	 * 获取Excel2007图片
+	 *
+	 * @param sheet 当前sheet对象
+	 * @param workbook 工作簿对象
+	 * @return Map key:图片单元格索引(1_1)String,value:图片流PictureData
+	 */
+	public static Map<String, PictureData> getSheetPictures07(XSSFSheet sheet, XSSFWorkbook workbook)
+	{
+		Map<String, PictureData> sheetIndexPicMap = new HashMap<String, PictureData>();
+		for (POIXMLDocumentPart dr : sheet.getRelations())
+		{
+			if (dr instanceof XSSFDrawing)
+			{
+				XSSFDrawing drawing = (XSSFDrawing) dr;
+				List<XSSFShape> shapes = drawing.getShapes();
+				for (XSSFShape shape : shapes)
+				{
+					if (shape instanceof XSSFPicture)
+					{
+						XSSFPicture pic = (XSSFPicture) shape;
+						XSSFClientAnchor anchor = pic.getPreferredSize();
+						CTMarker ctMarker = anchor.getFrom();
+						String picIndex = ctMarker.getRow() + "_" + ctMarker.getCol();
+						sheetIndexPicMap.put(picIndex, pic.getPictureData());
+					}
+				}
+			}
+		}
+		return sheetIndexPicMap;
+	}
+
+	/**
+	 * 获取字段注解信息
+	 */
+	public List<Object[]> getFields()
+	{
+		List<Object[]> fields = new ArrayList<Object[]>();
+		List<Field> tempFields = new ArrayList<>();
+		tempFields.addAll(Arrays.asList(clazz.getSuperclass().getDeclaredFields()));
+		tempFields.addAll(Arrays.asList(clazz.getDeclaredFields()));
+		for (Field field : tempFields)
+		{
+			// 单注解
+			if (field.isAnnotationPresent(Excel.class))
+			{
+				Excel attr = field.getAnnotation(Excel.class);
+				if (attr != null && (attr.type() == Type.ALL || attr.type() == type))
+				{
+					field.setAccessible(true);
+					fields.add(new Object[] { field, attr });
+				}
+			}
+
+			// 多注解
+			if (field.isAnnotationPresent(Excels.class))
+			{
+				Excels attrs = field.getAnnotation(Excels.class);
+				Excel[] excels = attrs.value();
+				for (Excel attr : excels)
+				{
+					if (attr != null && (attr.type() == Type.ALL || attr.type() == type))
+					{
+						field.setAccessible(true);
+						fields.add(new Object[] { field, attr });
+					}
+				}
+			}
+		}
+		return fields;
+	}