概述
最近在公司写单元测试时,从前台传入的参数是由 excel 数据转化的字节组,在后台中把字节数组转化为 XSSFSheet 后转成 VO 。所以在写单元测试时要把字节数组作为输入,之前没有遇到过这种情况,一开始尝试把后台把字节数据转化成 XSSFSheet 的方法模拟掉,行不通。
解决方法:
1、用 XSSFWorkbook 对象生成 Excel 的对象,添加数据,然后转化为字节数组。
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet();//添加Worksheet(不添加sheet时生成的xls文件打开时会报错)
XSSFRow row=sheet.createRow((short)(0)); //第一行
row.createCell(0).setCellValue("流水号"); //设置第一个(从0开始)单元格的数据
row.createCell(1).setCellValue("供应商名称"); //设置第二个(从0开始)单元格的数据
XSSFRowrow2=sheet.createRow((short)(1)); //第二行
row2.createCell(0).setCellValue("TBSO171010808930"); //设置第一个(从0开始)单元格的数据
row2.createCell(1).setCellValue("王***");//设置第二个(从0开始)单元格的数据
ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
workbook.write(os);
} catch (IOException e) {
e.printStackTrace();
}
byte[] bytes = os.toByteArray()2、手动新建一个 excel ,写入数据,保存到指定 test/main/source 目录中
String filePath ="/excelTestCase/manualCloseAccountsSettleOrder/manualSettleOrderTemplate.xlsx";
byte[] bytes =this.getBytes(filePath);
public byte[] getBytes(String filePath){
byte[] buffer = null;
try {
MockServletContext servletContext = new MockServletContext();
MockHttpServletRequest request = new MockHttpServletRequest(servletContext);
FlexContext.setThreadLocalHttpRequest(request);
SecurityUtil.getContextPath();
InputStream in = new ClassPathResource(filePath).getInputStream();
ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
byte[] b = new byte[1000];
int n;
while ((n = in.read(b)) != -1) {
bos.write(b, 0, n);
}
in.close();
bos.close();
buffer = bos.toByteArray();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return buffer;
}
最后
以上就是迷人手套为你收集整理的Java中生成excel,并进行数据的写入读出的全部内容,希望文章能够帮你解决Java中生成excel,并进行数据的写入读出所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复