Browse Source

优化读写逻辑

bugfix
zhuangjiaju 5 years ago
parent
commit
3f78c57e81
  1. 28
      src/main/java/com/alibaba/excel/converters/ConverterKeyBuild.java
  2. 10
      src/main/java/com/alibaba/excel/converters/DefaultConverterLoader.java
  3. 41
      src/main/java/com/alibaba/excel/converters/bytearray/BoxingByteArrayImageConverter.java
  4. 37
      src/main/java/com/alibaba/excel/converters/bytearray/ByteArrayImageConverter.java
  5. 41
      src/main/java/com/alibaba/excel/converters/file/FileImageConverter.java
  6. 41
      src/main/java/com/alibaba/excel/converters/inputstream/InputStreamImageConverter.java
  7. 41
      src/main/java/com/alibaba/excel/converters/string/StringImageConverter.java
  8. 6
      src/main/java/com/alibaba/excel/enums/CellDataTypeEnum.java
  9. 23
      src/main/java/com/alibaba/excel/metadata/CellData.java
  10. 46
      src/main/java/com/alibaba/excel/util/FileUtils.java
  11. 85
      src/main/java/com/alibaba/excel/util/IOUtils.java
  12. 29
      src/main/java/com/alibaba/excel/write/ExcelBuilderImpl.java
  13. 1
      src/main/java/com/alibaba/excel/write/style/column/SimpleColumnWidthStyleStrategy.java
  14. 4
      src/test/java/com/alibaba/easyexcel/test/core/converter/ConverterData.java
  15. 40
      src/test/java/com/alibaba/easyexcel/test/core/converter/ConverterDataTest.java
  16. 25
      src/test/java/com/alibaba/easyexcel/test/core/converter/ImageData.java
  17. 20
      src/test/java/com/alibaba/easyexcel/test/temp/StyleData.java
  18. 20
      src/test/java/com/alibaba/easyexcel/test/temp/StyleTest.java
  19. 8
      src/test/java/com/alibaba/easyexcel/test/util/TestFileUtil.java
  20. BIN
      src/test/resources/converter/img.jpg

28
src/main/java/com/alibaba/excel/converters/ConverterKeyBuild.java

@ -1,18 +1,40 @@
package com.alibaba.excel.converters; package com.alibaba.excel.converters;
import java.util.HashMap;
import java.util.Map;
import com.alibaba.excel.enums.CellDataTypeEnum; import com.alibaba.excel.enums.CellDataTypeEnum;
/** /**
* Converter unique key * Converter unique key.Consider that you can just use class as the key.
* *
* @author Jiaju Zhuang * @author Jiaju Zhuang
*/ */
public class ConverterKeyBuild { public class ConverterKeyBuild {
private static final Map<String, String> BOXING_MAP = new HashMap<String, String>(16);
static {
BOXING_MAP.put(int.class.getName(), Integer.class.getName());
BOXING_MAP.put(byte.class.getName(), Byte.class.getName());
BOXING_MAP.put(long.class.getName(), Long.class.getName());
BOXING_MAP.put(double.class.getName(), Double.class.getName());
BOXING_MAP.put(float.class.getName(), Float.class.getName());
BOXING_MAP.put(char.class.getName(), Character.class.getName());
BOXING_MAP.put(short.class.getName(), Short.class.getName());
BOXING_MAP.put(boolean.class.getName(), Boolean.class.getName());
}
public static String buildKey(Class clazz) { public static String buildKey(Class clazz) {
return clazz.getName(); String className = clazz.getName();
String boxingClassName = BOXING_MAP.get(clazz.getName());
if (boxingClassName == null) {
return className;
}
return boxingClassName;
} }
public static String buildKey(Class clazz, CellDataTypeEnum cellDataTypeEnum) { public static String buildKey(Class clazz, CellDataTypeEnum cellDataTypeEnum) {
return clazz.getName() + "-" + cellDataTypeEnum.toString(); return buildKey(clazz) + "-" + cellDataTypeEnum.toString();
} }
} }

10
src/main/java/com/alibaba/excel/converters/DefaultConverterLoader.java

@ -9,6 +9,8 @@ import com.alibaba.excel.converters.bigdecimal.BigDecimalStringConverter;
import com.alibaba.excel.converters.booleanconverter.BooleanBooleanConverter; import com.alibaba.excel.converters.booleanconverter.BooleanBooleanConverter;
import com.alibaba.excel.converters.booleanconverter.BooleanNumberConverter; import com.alibaba.excel.converters.booleanconverter.BooleanNumberConverter;
import com.alibaba.excel.converters.booleanconverter.BooleanStringConverter; import com.alibaba.excel.converters.booleanconverter.BooleanStringConverter;
import com.alibaba.excel.converters.bytearray.BoxingByteArrayImageConverter;
import com.alibaba.excel.converters.bytearray.ByteArrayImageConverter;
import com.alibaba.excel.converters.byteconverter.ByteBooleanConverter; import com.alibaba.excel.converters.byteconverter.ByteBooleanConverter;
import com.alibaba.excel.converters.byteconverter.ByteNumberConverter; import com.alibaba.excel.converters.byteconverter.ByteNumberConverter;
import com.alibaba.excel.converters.byteconverter.ByteStringConverter; import com.alibaba.excel.converters.byteconverter.ByteStringConverter;
@ -17,9 +19,11 @@ import com.alibaba.excel.converters.date.DateStringConverter;
import com.alibaba.excel.converters.doubleconverter.DoubleBooleanConverter; import com.alibaba.excel.converters.doubleconverter.DoubleBooleanConverter;
import com.alibaba.excel.converters.doubleconverter.DoubleNumberConverter; import com.alibaba.excel.converters.doubleconverter.DoubleNumberConverter;
import com.alibaba.excel.converters.doubleconverter.DoubleStringConverter; import com.alibaba.excel.converters.doubleconverter.DoubleStringConverter;
import com.alibaba.excel.converters.file.FileImageConverter;
import com.alibaba.excel.converters.floatconverter.FloatBooleanConverter; import com.alibaba.excel.converters.floatconverter.FloatBooleanConverter;
import com.alibaba.excel.converters.floatconverter.FloatNumberConverter; import com.alibaba.excel.converters.floatconverter.FloatNumberConverter;
import com.alibaba.excel.converters.floatconverter.FloatStringConverter; import com.alibaba.excel.converters.floatconverter.FloatStringConverter;
import com.alibaba.excel.converters.inputstream.InputStreamImageConverter;
import com.alibaba.excel.converters.integer.IntegerBooleanConverter; import com.alibaba.excel.converters.integer.IntegerBooleanConverter;
import com.alibaba.excel.converters.integer.IntegerNumberConverter; import com.alibaba.excel.converters.integer.IntegerNumberConverter;
import com.alibaba.excel.converters.integer.IntegerStringConverter; import com.alibaba.excel.converters.integer.IntegerStringConverter;
@ -52,7 +56,7 @@ public class DefaultConverterLoader {
if (defaultWriteConverter != null) { if (defaultWriteConverter != null) {
return defaultWriteConverter; return defaultWriteConverter;
} }
defaultWriteConverter = new HashMap<String, Converter>(16); defaultWriteConverter = new HashMap<String, Converter>(32);
putWriteConverter(new BigDecimalNumberConverter()); putWriteConverter(new BigDecimalNumberConverter());
putWriteConverter(new BooleanBooleanConverter()); putWriteConverter(new BooleanBooleanConverter());
putWriteConverter(new ByteNumberConverter()); putWriteConverter(new ByteNumberConverter());
@ -63,6 +67,10 @@ public class DefaultConverterLoader {
putWriteConverter(new LongNumberConverter()); putWriteConverter(new LongNumberConverter());
putWriteConverter(new ShortNumberConverter()); putWriteConverter(new ShortNumberConverter());
putWriteConverter(new StringStringConverter()); putWriteConverter(new StringStringConverter());
putWriteConverter(new FileImageConverter());
putWriteConverter(new InputStreamImageConverter());
putWriteConverter(new ByteArrayImageConverter());
putWriteConverter(new BoxingByteArrayImageConverter());
return defaultWriteConverter; return defaultWriteConverter;
} }

41
src/main/java/com/alibaba/excel/converters/bytearray/BoxingByteArrayImageConverter.java

@ -0,0 +1,41 @@
package com.alibaba.excel.converters.bytearray;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
/**
* Boxing Byte array and image converter
*
* @author Jiaju Zhuang
*/
public class BoxingByteArrayImageConverter implements Converter<Byte[]> {
@Override
public Class supportJavaTypeKey() {
return Byte[].class;
}
@Override
public CellDataTypeEnum supportExcelTypeKey() {
return CellDataTypeEnum.IMAGE;
}
@Override
public Byte[] convertToJavaData(CellData cellData, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) {
throw new UnsupportedOperationException("Cannot convert images to byte arrays");
}
@Override
public CellData convertToExcelData(Byte[] value, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) {
byte[] byteValue = new byte[value.length];
for (int i = 0; i < value.length; i++) {
byteValue[i] = value[i];
}
return new CellData(byteValue);
}
}

37
src/main/java/com/alibaba/excel/converters/bytearray/ByteArrayImageConverter.java

@ -0,0 +1,37 @@
package com.alibaba.excel.converters.bytearray;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
/**
* Byte array and image converter
*
* @author Jiaju Zhuang
*/
public class ByteArrayImageConverter implements Converter<byte[]> {
@Override
public Class supportJavaTypeKey() {
return byte[].class;
}
@Override
public CellDataTypeEnum supportExcelTypeKey() {
return CellDataTypeEnum.IMAGE;
}
@Override
public byte[] convertToJavaData(CellData cellData, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) {
throw new UnsupportedOperationException("Cannot convert images to byte arrays");
}
@Override
public CellData convertToExcelData(byte[] value, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) {
return new CellData(value);
}
}

41
src/main/java/com/alibaba/excel/converters/file/FileImageConverter.java

@ -0,0 +1,41 @@
package com.alibaba.excel.converters.file;
import java.io.File;
import java.io.IOException;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.alibaba.excel.util.FileUtils;
/**
* File and image converter
*
* @author Jiaju Zhuang
*/
public class FileImageConverter implements Converter<File> {
@Override
public Class supportJavaTypeKey() {
return File.class;
}
@Override
public CellDataTypeEnum supportExcelTypeKey() {
return CellDataTypeEnum.IMAGE;
}
@Override
public File convertToJavaData(CellData cellData, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) {
throw new UnsupportedOperationException("Cannot convert images to file");
}
@Override
public CellData convertToExcelData(File value, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) throws IOException {
return new CellData(FileUtils.readFileToByteArray(value));
}
}

41
src/main/java/com/alibaba/excel/converters/inputstream/InputStreamImageConverter.java

@ -0,0 +1,41 @@
package com.alibaba.excel.converters.inputstream;
import java.io.IOException;
import java.io.InputStream;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.alibaba.excel.util.IOUtils;
/**
* File and image converter
*
* @author Jiaju Zhuang
*/
public class InputStreamImageConverter implements Converter<InputStream> {
@Override
public Class supportJavaTypeKey() {
return InputStream.class;
}
@Override
public CellDataTypeEnum supportExcelTypeKey() {
return CellDataTypeEnum.IMAGE;
}
@Override
public InputStream convertToJavaData(CellData cellData, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) {
throw new UnsupportedOperationException("Cannot convert images to input stream");
}
@Override
public CellData convertToExcelData(InputStream value, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) throws IOException {
return new CellData(IOUtils.toByteArray(value));
}
}

41
src/main/java/com/alibaba/excel/converters/string/StringImageConverter.java

@ -0,0 +1,41 @@
package com.alibaba.excel.converters.string;
import java.io.File;
import java.io.IOException;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.alibaba.excel.util.FileUtils;
/**
* String and image converter
*
* @author Jiaju Zhuang
*/
public class StringImageConverter implements Converter<String> {
@Override
public Class supportJavaTypeKey() {
return String.class;
}
@Override
public CellDataTypeEnum supportExcelTypeKey() {
return CellDataTypeEnum.IMAGE;
}
@Override
public String convertToJavaData(CellData cellData, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) {
throw new UnsupportedOperationException("Cannot convert images to string");
}
@Override
public CellData convertToExcelData(String value, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) throws IOException {
return new CellData(FileUtils.readFileToByteArray(new File(value)));
}
}

6
src/main/java/com/alibaba/excel/enums/CellDataTypeEnum.java

@ -35,7 +35,11 @@ public enum CellDataTypeEnum {
/** /**
* error * error
*/ */
ERROR; ERROR,
/**
* Images are currently supported only when writing
*/
IMAGE;
private static final Map<String, CellDataTypeEnum> TYPE_ROUTING_MAP = new HashMap<String, CellDataTypeEnum>(16); private static final Map<String, CellDataTypeEnum> TYPE_ROUTING_MAP = new HashMap<String, CellDataTypeEnum>(16);
static { static {

23
src/main/java/com/alibaba/excel/metadata/CellData.java

@ -23,12 +23,13 @@ public class CellData {
private Boolean booleanValue; private Boolean booleanValue;
private Boolean formula; private Boolean formula;
private String formulaValue; private String formulaValue;
private byte[] imageValue;
/** /**
* The number formatting * The number formatting.Currently only supported when reading
*/ */
private Integer dataFormat; private Integer dataFormat;
/** /**
* The string of number formatting * The string of number formatting.Currently only supported when reading
*/ */
private String dataFormatString; private String dataFormatString;
@ -39,6 +40,7 @@ public class CellData {
this.booleanValue = other.booleanValue; this.booleanValue = other.booleanValue;
this.formula = other.formula; this.formula = other.formula;
this.formulaValue = other.formulaValue; this.formulaValue = other.formulaValue;
this.imageValue = other.imageValue;
this.dataFormat = other.dataFormat; this.dataFormat = other.dataFormat;
this.dataFormatString = other.dataFormatString; this.dataFormatString = other.dataFormatString;
} }
@ -68,6 +70,15 @@ public class CellData {
this.formula = Boolean.FALSE; this.formula = Boolean.FALSE;
} }
public CellData(byte[] imageValue) {
if (imageValue == null) {
throw new IllegalArgumentException("ImageValue can not be null");
}
this.type = CellDataTypeEnum.IMAGE;
this.imageValue = imageValue;
this.formula = Boolean.FALSE;
}
public CellData(Boolean booleanValue) { public CellData(Boolean booleanValue) {
if (booleanValue == null) { if (booleanValue == null) {
throw new IllegalArgumentException("BooleanValue can not be null"); throw new IllegalArgumentException("BooleanValue can not be null");
@ -133,6 +144,14 @@ public class CellData {
this.formulaValue = formulaValue; this.formulaValue = formulaValue;
} }
public byte[] getImageValue() {
return imageValue;
}
public void setImageValue(byte[] imageValue) {
this.imageValue = imageValue;
}
public Integer getDataFormat() { public Integer getDataFormat() {
return dataFormat; return dataFormat;
} }

46
src/main/java/com/alibaba/excel/util/FileUtils.java

@ -1,6 +1,8 @@
package com.alibaba.excel.util; package com.alibaba.excel.util;
import java.io.File; import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
@ -23,6 +25,50 @@ public class FileUtils {
private static final String CACHE = "excache"; private static final String CACHE = "excache";
private static final int WRITE_BUFF_SIZE = 8192; private static final int WRITE_BUFF_SIZE = 8192;
/**
* Reads the contents of a file into a byte array. * The file is always closed.
*
* @param file
* @return
* @throws IOException
*/
public static byte[] readFileToByteArray(final File file) throws IOException {
InputStream in = openInputStream(file);
try {
final long fileLength = file.length();
return fileLength > 0 ? IOUtils.toByteArray(in, (int)fileLength) : IOUtils.toByteArray(in);
} finally {
in.close();
}
}
/**
* Opens a {@link FileInputStream} for the specified file, providing better error messages than simply calling
* <code>new FileInputStream(file)</code>.
* <p>
* At the end of the method either the stream will be successfully opened, or an exception will have been thrown.
* <p>
* An exception is thrown if the file does not exist. An exception is thrown if the file object exists but is a
* directory. An exception is thrown if the file exists but cannot be read.
*
* @param file
* @return
* @throws IOException
*/
public static FileInputStream openInputStream(final File file) throws IOException {
if (file.exists()) {
if (file.isDirectory()) {
throw new IOException("File '" + file + "' exists but is a directory");
}
if (file.canRead() == false) {
throw new IOException("File '" + file + "' cannot be read");
}
} else {
throw new FileNotFoundException("File '" + file + "' does not exist");
}
return new FileInputStream(file);
}
/** /**
* Write inputStream to file * Write inputStream to file
* *

85
src/main/java/com/alibaba/excel/util/IOUtils.java

@ -0,0 +1,85 @@
package com.alibaba.excel.util;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* IO Utils
*
* @author Jiaju Zhuang
*/
public class IOUtils {
public static final int EOF = -1;
/**
* The default buffer size ({@value}) to use for
*/
private static final int DEFAULT_BUFFER_SIZE = 1024 * 4;
/**
* Gets the contents of an InputStream as a byte[].
*
* @param input
* @return
* @throws IOException
*/
public static byte[] toByteArray(final InputStream input) throws IOException {
final ByteArrayOutputStream output = new ByteArrayOutputStream();
try {
copy(input, output);
return output.toByteArray();
} finally {
output.toByteArray();
}
}
/**
* Gets the contents of an InputStream as a byte[].
*
* @param input
* @param size
* @return
* @throws IOException
*/
public static byte[] toByteArray(final InputStream input, final int size) throws IOException {
if (size < 0) {
throw new IllegalArgumentException("Size must be equal or greater than zero: " + size);
}
if (size == 0) {
return new byte[0];
}
final byte[] data = new byte[size];
int offset = 0;
int read;
while (offset < size && (read = input.read(data, offset, size - offset)) != EOF) {
offset += read;
}
if (offset != size) {
throw new IOException("Unexpected read size. current: " + offset + ", expected: " + size);
}
return data;
}
/**
* Copies bytes
*
* @param input
* @param output
* @return
* @throws IOException
*/
public static int copy(final InputStream input, final OutputStream output) throws IOException {
long count = 0;
int n;
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
while (EOF != (n = input.read(buffer))) {
output.write(buffer, 0, n);
count += n;
}
if (count > Integer.MAX_VALUE) {
return -1;
}
return (int)count;
}
}

29
src/main/java/com/alibaba/excel/write/ExcelBuilderImpl.java

@ -8,8 +8,13 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.ClientAnchor;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.Drawing;
import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddress; import org.apache.poi.ss.util.CellRangeAddress;
import com.alibaba.excel.context.WriteContext; import com.alibaba.excel.context.WriteContext;
@ -303,12 +308,36 @@ public class ExcelBuilderImpl implements ExcelBuilder {
case NUMBER: case NUMBER:
cell.setCellValue(cellData.getDoubleValue()); cell.setCellValue(cellData.getDoubleValue());
return cellData; return cellData;
case IMAGE:
setImageValue(cellData, cell);
return cellData;
default: default:
throw new ExcelDataConvertException("Not supported data:" + value + " return type:" + cell.getCellType() throw new ExcelDataConvertException("Not supported data:" + value + " return type:" + cell.getCellType()
+ "at row:" + cell.getRow().getRowNum()); + "at row:" + cell.getRow().getRowNum());
} }
} }
private void setImageValue(CellData cellData, Cell cell) {
Sheet sheet = cell.getSheet();
int index = sheet.getWorkbook().addPicture(cellData.getImageValue(), HSSFWorkbook.PICTURE_TYPE_PNG);
Drawing drawing = sheet.getDrawingPatriarch();
if (drawing == null) {
drawing = sheet.createDrawingPatriarch();
}
CreationHelper helper = sheet.getWorkbook().getCreationHelper();
ClientAnchor anchor = helper.createClientAnchor();
anchor.setDx1(0);
anchor.setDx2(0);
anchor.setDy1(0);
anchor.setDy2(0);
anchor.setCol1(cell.getColumnIndex());
anchor.setCol2(cell.getColumnIndex() + 1);
anchor.setRow1(cell.getRowIndex());
anchor.setRow2(cell.getRowIndex() + 1);
anchor.setAnchorType(ClientAnchor.AnchorType.DONT_MOVE_AND_RESIZE);
drawing.createPicture(anchor, index);
}
private CellData convert(WriteHolder currentWriteHolder, Class clazz, Cell cell, Object value, private CellData convert(WriteHolder currentWriteHolder, Class clazz, Cell cell, Object value,
ExcelContentProperty excelContentProperty) { ExcelContentProperty excelContentProperty) {
if (value instanceof CellData) { if (value instanceof CellData) {

1
src/main/java/com/alibaba/excel/write/style/column/SimpleColumnWidthStyleStrategy.java

@ -13,7 +13,6 @@ public class SimpleColumnWidthStyleStrategy extends AbstractHeadColumnWidthStyle
/** /**
* *
* @param columnWidth * @param columnWidth
*
*/ */
public SimpleColumnWidthStyleStrategy(Integer columnWidth) { public SimpleColumnWidthStyleStrategy(Integer columnWidth) {
this.columnWidth = columnWidth; this.columnWidth = columnWidth;

4
src/test/java/com/alibaba/easyexcel/test/core/converter/ConverterData.java

@ -20,7 +20,7 @@ public class ConverterData {
@ExcelProperty("大数") @ExcelProperty("大数")
private BigDecimal bigDecimal; private BigDecimal bigDecimal;
@ExcelProperty("长整型") @ExcelProperty("长整型")
private Long longData; private long longData;
@ExcelProperty("整型") @ExcelProperty("整型")
private Integer integerData; private Integer integerData;
@ExcelProperty("短整型") @ExcelProperty("短整型")
@ -28,7 +28,7 @@ public class ConverterData {
@ExcelProperty("字节型") @ExcelProperty("字节型")
private Byte byteData; private Byte byteData;
@ExcelProperty("双精度浮点型") @ExcelProperty("双精度浮点型")
private Double doubleData; private double doubleData;
@ExcelProperty("浮点型") @ExcelProperty("浮点型")
private Float floatData; private Float floatData;
@ExcelProperty("字符串") @ExcelProperty("字符串")

40
src/test/java/com/alibaba/easyexcel/test/core/converter/ConverterDataTest.java

@ -1,6 +1,7 @@
package com.alibaba.easyexcel.test.core.converter; package com.alibaba.easyexcel.test.core.converter;
import java.io.File; import java.io.File;
import java.io.InputStream;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -12,9 +13,9 @@ import org.junit.runners.MethodSorters;
import com.alibaba.easyexcel.test.util.TestFileUtil; import com.alibaba.easyexcel.test.util.TestFileUtil;
import com.alibaba.excel.EasyExcel; import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.metadata.CellData; import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.util.DateUtils; import com.alibaba.excel.util.DateUtils;
import com.alibaba.excel.util.FileUtils;
/** /**
* *
@ -25,11 +26,15 @@ public class ConverterDataTest {
private static File file07; private static File file07;
private static File file03; private static File file03;
private static File fileImage07;
private static File fileImage03;
@BeforeClass @BeforeClass
public static void init() { public static void init() {
file07 = TestFileUtil.createNewFile("converter07.xlsx"); file07 = TestFileUtil.createNewFile("converter07.xlsx");
file03 = TestFileUtil.createNewFile("converter03.xls"); file03 = TestFileUtil.createNewFile("converter03.xls");
fileImage07 = TestFileUtil.createNewFile("converterImage07.xlsx");
fileImage03 = TestFileUtil.createNewFile("converterImage03.xls");
} }
@Test @Test
@ -57,9 +62,38 @@ public class ConverterDataTest {
readAllConverter("converter" + File.separator + "converter03.xls"); readAllConverter("converter" + File.separator + "converter03.xls");
} }
@Test
public void T05WriteImage07() throws Exception {
writeImage(fileImage07);
}
@Test
public void T06WriteImage03() throws Exception {
writeImage(fileImage03);
}
private void writeImage(File file) throws Exception {
InputStream inputStream = null;
try {
List<ImageData> list = new ArrayList<ImageData>();
ImageData imageData = new ImageData();
list.add(imageData);
String imagePath = TestFileUtil.getPath() + "converter" + File.separator + "img.jpg";
imageData.setByteArray(FileUtils.readFileToByteArray(new File(imagePath)));
imageData.setFile(new File(imagePath));
imageData.setString(imagePath);
inputStream = FileUtils.openInputStream(new File(imagePath));
imageData.setInputStream(inputStream);
EasyExcel.write(file, ImageData.class).sheet().doWrite(list);
} finally {
if (inputStream != null) {
inputStream.close();
}
}
}
private void readAllConverter(String fileName) { private void readAllConverter(String fileName) {
EasyExcel EasyExcel.read(TestFileUtil.readFile(fileName), ReadAllConverterData.class, new ReadAllConverterDataListener())
.read(TestFileUtil.readFile(fileName), ReadAllConverterData.class, new ReadAllConverterDataListener())
.sheet().doRead(); .sheet().doRead();
} }

25
src/test/java/com/alibaba/easyexcel/test/core/converter/ImageData.java

@ -0,0 +1,25 @@
package com.alibaba.easyexcel.test.core.converter;
import java.io.File;
import java.io.InputStream;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.write.style.ColumnWidth;
import com.alibaba.excel.annotation.write.style.ContentRowHeight;
import com.alibaba.excel.converters.string.StringImageConverter;
import lombok.Data;
/**
* @author Jiaju Zhuang
*/
@Data
@ContentRowHeight(500)
@ColumnWidth(500 / 8)
public class ImageData {
private File file;
private InputStream inputStream;
@ExcelProperty(converter = StringImageConverter.class)
private String string;
private byte[] byteArray;
}

20
src/test/java/com/alibaba/easyexcel/test/temp/StyleData.java

@ -0,0 +1,20 @@
package com.alibaba.easyexcel.test.temp;
import java.util.List;
import lombok.Data;
/**
*
* @author Jiaju Zhuang
**/
@Data
public class StyleData {
private byte[] byteValue;
private Byte[] byteValue2;
private byte byteValue1;
private Byte byteValue4;
private byte byteValue3;
private String[] ss;
private List<String> s1s;
}

20
src/test/java/com/alibaba/easyexcel/test/temp/StyleTest.java

@ -2,6 +2,7 @@ package com.alibaba.easyexcel.test.temp;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.InputStream; import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
@ -18,6 +19,7 @@ import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory; import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.junit.Ignore; import org.junit.Ignore;
import org.junit.Test; import org.junit.Test;
import org.slf4j.Logger; import org.slf4j.Logger;
@ -118,6 +120,24 @@ public class StyleTest {
System.out.println(ff.format(new Date())); System.out.println(ff.format(new Date()));
} }
@Test
public void testFormatter2() throws Exception {
StyleData styleData = new StyleData();
Field field = styleData.getClass().getDeclaredField("byteValue");
LOGGER.info("filed:{}", field.getType().getName());
field = styleData.getClass().getDeclaredField("byteValue2");
LOGGER.info("filed:{}", field.getType().getName());
field = styleData.getClass().getDeclaredField("byteValue4");
LOGGER.info("filed:{}", field.getType());
field = styleData.getClass().getDeclaredField("byteValue3");
LOGGER.info("filed:{}", field.getType());
}
@Test
public void testFormatter3() throws Exception {
LOGGER.info("filed:{}", Byte.class == Byte.class);
}
private void isDate(Cell cell) { private void isDate(Cell cell) {
System.out.println( System.out.println(
DateUtil.isADateFormat(cell.getCellStyle().getDataFormat(), cell.getCellStyle().getDataFormatString())); DateUtil.isADateFormat(cell.getCellStyle().getDataFormat(), cell.getCellStyle().getDataFormatString()));

8
src/test/java/com/alibaba/easyexcel/test/util/TestFileUtil.java

@ -13,10 +13,6 @@ public class TestFileUtil {
return TestFileUtil.class.getResource("/").getPath(); return TestFileUtil.class.getResource("/").getPath();
} }
public static File readFile(String pathName) {
return new File(getPath() + pathName);
}
public static File createNewFile(String pathName) { public static File createNewFile(String pathName) {
File file = new File(getPath() + pathName); File file = new File(getPath() + pathName);
if (file.exists()) { if (file.exists()) {
@ -29,4 +25,8 @@ public class TestFileUtil {
return file; return file;
} }
public static File readFile(String pathName) {
return new File(getPath() + pathName);
}
} }

BIN
src/test/resources/converter/img.jpg

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Loading…
Cancel
Save