spring读取、写入、后台接收、前后台导出excel。
引入
<!-- poi office -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.16</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.16</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>3.16</version>
</dependency>
读取
package excelHelper;
import org.apache.poi.ss.usermodel.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
public class ReadExcel {
public static void main(String[] args) throws Exception {
InputStream is = new FileInputStream(new File("d://测试.xls"));
//根据输入流创建Workbook对象
Workbook wb = WorkbookFactory.create(is);
//get到Sheet对象
Sheet sheet = wb.getSheetAt(0);
//这个必须用接口
for(Row row : sheet){
for(Cell cell : row){
//cell.getCellType是获得cell里面保存的值的type
//如Cell.CELL_TYPE_STRING
switch(cell.getCellTypeEnum()){
case BOOLEAN:
//得到Boolean对象的方法
System.out.print(cell.getBooleanCellValue()+" ");
break;
case NUMERIC:
//先看是否是日期格式
if(DateUtil.isCellDateFormatted(cell)){
//读取日期格式
System.out.print(cell.getDateCellValue()+" ");
}else{
//读取数字
System.out.print(cell.getNumericCellValue()+" ");
}
break;
case FORMULA:
//读取公式
System.out.print(cell.getCellFormula()+" ");
break;
case STRING:
//读取String
System.out.print(cell.getRichStringCellValue().toString()+" ");
break;
}
}
System.out.println("");
}
}
}
写入
public class SummaryHSSF {
public static void main(String[] args) throws IOException {
//创建Workbook对象(这一个对象代表着对应的一个Excel文件)
//HSSFWorkbook表示以xls为后缀名的文件
Workbook wb = new XSSFWorkbook();
//Workbook wb2 = new HSSFWorkbook();//如果是xls文件,就用这个
//获得CreationHelper对象,这个应该是一个帮助类
CreationHelper helper = wb.getCreationHelper();
//创建Sheet并给名字(表示Excel的一个Sheet)
Sheet sheet1 = wb.createSheet("HSSF_Sheet_1");
Sheet sheet2 = wb.createSheet("HSSF_Sheet_2");
//Row表示一行Cell表示一列
Row row = null;
Cell cell = null;
for(int i=0;i<60;i=i+2){
//获得这个sheet的第i行
row = sheet1.createRow(i);
//设置行长度自动
//row.setHeight((short)500);
row.setHeightInPoints(20);
//row.setZeroHeight(true);
for(int j=0;j<25;j++){
//设置每个sheet每一行的宽度,自动,根据需求自行确定
sheet1.autoSizeColumn(j+1, true);
//创建一个基本的样式
CellStyle cellStyle = SummaryHSSF.createStyleCell(wb);
//获得这一行的每j列
cell = row.createCell(j);
if(j==0){
//设置文字在单元格里面的位置
cellStyle = SummaryHSSF.setCellStyleAlignment(cellStyle, HorizontalAlignment.GENERAL, VerticalAlignment.CENTER);
//先创建字体样式,并把这个样式加到单元格的字体里面
cellStyle.setFont(createFonts(wb));
//把这个样式加到单元格里面
cell.setCellStyle(cellStyle);
//给单元格设值
cell.setCellValue(true);
}else if(j==1){
//设置文字在单元格里面的位置
cellStyle = SummaryHSSF.setCellStyleAlignment(cellStyle, HorizontalAlignment.GENERAL, VerticalAlignment.CENTER);
//设置这个样式的格式(Format)
cellStyle = SummaryHSSF.setCellFormat(helper,cellStyle, "#,##0.0000");
//先创建字体样式,并把这个样式加到单元格的字体里面
cellStyle.setFont(createFonts(wb));
//把这个样式加到单元格里面
cell.setCellStyle(cellStyle);
//给单元格设值
cell.setCellValue(new Double(2008.2008));
}else if(j==2){
cellStyle = SummaryHSSF.setCellStyleAlignment(cellStyle, HorizontalAlignment.GENERAL, VerticalAlignment.CENTER);
cellStyle.setFont(createFonts(wb));
cell.setCellStyle(cellStyle);
cell.setCellValue(helper.createRichTextString("RichString"+i+j));
}else if(j==3){
cellStyle = SummaryHSSF.setCellStyleAlignment(cellStyle, HorizontalAlignment.GENERAL, VerticalAlignment.CENTER);
cellStyle = SummaryHSSF.setCellFormat(helper,cellStyle, "MM-yyyy-dd");
cell.setCellStyle(cellStyle);
cell.setCellValue(new Date());
}else if(j==24){
cellStyle = SummaryHSSF.setCellStyleAlignment(cellStyle, HorizontalAlignment.GENERAL, VerticalAlignment.CENTER);
cellStyle.setFont(createFonts(wb));
//设置公式
cell.setCellFormula("SUM(E"+(i+1)+":X"+(i+1)+")");
}else{
cellStyle = SummaryHSSF.setCellStyleAlignment(cellStyle, HorizontalAlignment.GENERAL, VerticalAlignment.CENTER);
cellStyle = SummaryHSSF.setFillBackgroundColors(cellStyle,IndexedColors.ORANGE.getIndex(),IndexedColors.ORANGE.getIndex(),FillPatternType.SOLID_FOREGROUND);
cell.setCellStyle(cellStyle);
cell.setCellValue(1);
}
}
}
//输出x
OutputStream os = new FileOutputStream(new File("d://测试.xlsx"));
wb.write(os);
os.close();
}
/**
* 边框
* @param wb
* @return
*/
public static CellStyle createStyleCell(Workbook wb){
CellStyle cellStyle = wb.createCellStyle();
//设置一个单元格边框颜色
cellStyle.setBorderBottom(BorderStyle.THIN);
cellStyle.setBorderTop(BorderStyle.THIN);
cellStyle.setBorderLeft(BorderStyle.THIN);
cellStyle.setBorderRight(BorderStyle.THIN);
//设置一个单元格边框颜色
cellStyle.setRightBorderColor(IndexedColors.BLACK.getIndex());
cellStyle.setLeftBorderColor(IndexedColors.BLACK.getIndex());
cellStyle.setBottomBorderColor(IndexedColors.BLACK.getIndex());
cellStyle.setTopBorderColor(IndexedColors.BLACK.getIndex());
return cellStyle;
}
/**
* 设置文字在单元格里面的位置
* CellStyle.ALIGN_CENTER
* CellStyle.VERTICAL_CENTER
* @param cellStyle
* @param halign
* @param valign
* @return
*/
public static CellStyle setCellStyleAlignment(CellStyle cellStyle,HorizontalAlignment halign,VerticalAlignment valign){
//设置上下
cellStyle.setAlignment(HorizontalAlignment.GENERAL);
//设置左右
cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
return cellStyle;
}
/**
* 格式化单元格
* 如#,##0.00,m/d/yy去HSSFDataFormat或XSSFDataFormat里面找
* @param cellStyle
* @param fmt
* @return
*/
public static CellStyle setCellFormat(CreationHelper helper,CellStyle cellStyle,String fmt){
//还可以用其它方法创建format
cellStyle.setDataFormat(helper.createDataFormat().getFormat(fmt));
return cellStyle;
}
/**
* 前景和背景填充的着色
* @param cellStyle
* @param bg IndexedColors.ORANGE.getIndex();
* @param fg IndexedColors.ORANGE.getIndex();
* @param fp CellStyle.SOLID_FOREGROUND
* @return
*/
public static CellStyle setFillBackgroundColors(CellStyle cellStyle, short bg, short fg, FillPatternType fp){
cellStyle.setFillBackgroundColor(bg);
cellStyle.setFillForegroundColor(fg);
cellStyle.setFillPattern(fp);
return cellStyle;
}
/**
* 设置字体
* @param wb
* @return
*/
public static Font createFonts(Workbook wb){
//创建Font对象
Font font = wb.createFont();
//设置字体
font.setFontName("黑体");
//着色
font.setColor(IndexedColors.BLUE.getIndex());
//斜体
font.setItalic(true);
//字体大小
font.setFontHeight((short)300);
return font;
}
}
后端接收
@RequestMapping(value = "/import", method = RequestMethod.POST)
public String importLogisticsCcode(@RequestParam("fileName") MultipartFile file) throws Exception {
// 获取文件名
String fileName = file.getOriginalFilename();
if (StringUtils.isEmpty(fileName)){
return "文件不能为空";
}
// 获取文件后缀
String prefix=fileName.substring(fileName.lastIndexOf("."));
if (!prefix.toLowerCase().contains("xls") || !prefix.toLowerCase().contains("xlsx") ){
return "文件格式异常,请上传Excel文件格式";
}
// 防止生成的临时文件重复-建议使用UUID
final File excelFile = File.createTempFile(System.currentTimeMillis()+"", prefix);
file.transferTo(excelFile);
//由于2003和2007的版本所使用的接口不一样,所以这里统一用Workbook做兼容
boolean isExcel2003 = prefix.toLowerCase().endsWith("xls")?true:false;
Workbook workbook = null;
if(isExcel2003){
workbook = new HSSFWorkbook(new FileInputStream(excelFile));
}else{
workbook = new XSSFWorkbook(new FileInputStream(excelFile));
}
//Excel表中的内容
List<Map<String,Object>> list = new ArrayList<>();
Sheet sheet = workbook.getSheetAt(0);
//这里重1开始,跳过了标题,直接从第二行开始解析
for(int i=1; i<sheet.getLastRowNum()+1; i++) {
Row row =sheet.getRow(i);
//设置行格式和验证start 这里最好做成一个方法,免得代码多处复制
if(row.getCell(0)!=null){
row.getCell(0).setCellType(CellType.STRING);
}
if(row.getCell(1)!=null){
row.getCell(1).setCellType(CellType.STRING);
}
if(row.getCell(2)!=null){
row.getCell(2).setCellType(CellType.STRING);
}
String orderCode = row.getCell(0).getStringCellValue(); //订单编号
if (StringUtils.isEmpty(orderCode)){
return "第" + i+"行,第1列不能为空!";
}
String logisticsCompanyCode = row.getCell(1).getStringCellValue();
if (StringUtils.isEmpty(logisticsCompanyCode)){
return "第" + i+"行,第2列不能为空!";
}
String logisticsCode = row.getCell(2).getStringCellValue();
if (StringUtils.isEmpty(logisticsCode)){
return "第" + i+"行,第3列不能为空!";
}
//设置行格式和验证end
//组装列表
Map<String,Object> map = new HashMap<>();
map.put("orderCode",orderCode);
map.put("logisticsCompanyCode",logisticsCompanyCode);
map.put("logisticsCode",logisticsCode);
list.add(map);
}
//删除临时转换的文件
if (excelFile.exists()) {
excelFile.delete();
}
//list就是具体内容,剩下的就是自己处理具体业务了
System.out.println("上传的内容就是这个了:" + list);
}
前后端导出
controller设置header格式
@GetMapping("/export")
public void export(Long[] ids,HttpServletResponse response) throws IOException {
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
List<Order> order=orderService.findList(ids);
Date currentTime = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dataTime=formatter.format(currentTime);
//获取收货单的字节数组
byte[] content = orderService.exportOrders(order);
InputStream is = new ByteArrayInputStream(content);
String fileName = dataTime+"发货单";
//页面弹层下载
response.reset();
response.setContentType("application/vnd.ms-excel;charset=utf-8");
response.setHeader("Content-Disposition", "attachment;filename="
+ new String((fileName + ".xls").getBytes(), "iso-8859-1"));
ServletOutputStream out = response.getOutputStream();
//流输出
bis = new BufferedInputStream(is);
bos = new BufferedOutputStream(out);
byte[] buff = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
out.write(buff, 0, bytesRead);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
//关流
if (bis != null)
bis.close();
if (bos != null)
bos.close();
}
}
service获取并设置excel的所有内容
public byte[] exportOrders(List<Order> orders) {
ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
Date currentTime = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String dataTime=formatter.format(currentTime);
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("发货单");
//设置字体
HSSFFont font = workbook.createFont();
font.setFontHeightInPoints((short)11); //字体高度
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); //字体颜色
font.setFontName("宋体"); //字体
//生成标题样式
HSSFCellStyle style = workbook.createCellStyle();
style.setFont(font);
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
//创建第一行
HSSFRow row = sheet.createRow(0);
//设置行高
row.setHeight((short)(30*20));
HSSFCell cell = row.createCell(0);
//设置大标题
cell.setCellValue(dataTime+"发货单");
cell.setCellStyle(style);
row = sheet.createRow( 1);
row.setHeight((short)(25*20));
//设置小标题
cell = row.createCell(0);
cell.setCellValue("序号");
cell.setCellStyle(style);
cell = row.createCell(1);
cell.setCellValue("订单编号");
cell.setCellStyle(style);
cell = row.createCell(2);
cell.setCellValue("订单创建日期");
cell.setCellStyle(style);
cell = row.createCell(3);
cell.setCellValue("会员用户名");
cell.setCellStyle(style);
cell = row.createCell(4);
cell.setCellValue("商品名称");
cell.setCellStyle(style);
cell = row.createCell(5);
cell.setCellValue("数量");
cell.setCellStyle(style);
cell = row.createCell(6);
cell.setCellValue("单位");
cell.setCellStyle(style);
cell = row.createCell(7);
cell.setCellValue("规格");
cell.setCellStyle(style);
cell = row.createCell(8);
cell.setCellValue("商品分类");
cell.setCellStyle(style);
cell = row.createCell(9);
cell.setCellValue("是否组合支付");
cell.setCellStyle(style);
cell = row.createCell(10);
cell.setCellValue("人民币");
cell.setCellStyle(style);
cell = row.createCell(11);
cell.setCellValue("积分类型");
cell.setCellStyle(style);
cell = row.createCell(12);
cell.setCellValue("积分");
cell.setCellStyle(style);
cell = row.createCell(13);
cell.setCellValue("收件人");
cell.setCellStyle(style);
cell = row.createCell(14);
cell.setCellValue("收货手机号");
cell.setCellStyle(style);
cell = row.createCell(15);
cell.setCellValue("收货人地址");
cell.setCellStyle(style);
cell = row.createCell(16);
cell.setCellValue("邮编");
cell.setCellStyle(style);
cell = row.createCell(17);
cell.setCellValue("状态");
cell.setCellStyle(style);
cell = row.createCell(18);
cell.setCellValue("快递公司");
cell.setCellStyle(style);
cell = row.createCell(19);
cell.setCellValue("快递单号");
cell.setCellStyle(style);
// 合并单元格
CellRangeAddress cra =new CellRangeAddress(0, 0, 0, 19); // 起始行, 终止行, 起始列, 终止列
//CellRangeAddress cra1 =new CellRangeAddress(1, 1, 9, 10); // 起始行, 终止行, 起始列, 终止列
sheet.addMergedRegion(cra);
//sheet.addMergedRegion(cra1);
//设置列宽
sheet.setColumnWidth(0,6*256);
sheet.setColumnWidth(1,15*256);
sheet.setColumnWidth(2,21*256);
sheet.setColumnWidth(3,14*256);
sheet.setColumnWidth(4,11*256);
sheet.setColumnWidth(5,6*256);
sheet.setColumnWidth(6,6*256);
sheet.setColumnWidth(7,13*256);
sheet.setColumnWidth(8,13*256);
sheet.setColumnWidth(9,13*256);
sheet.setColumnWidth(10,11*256);
sheet.setColumnWidth(11,11*256);
sheet.setColumnWidth(12,11*256);
sheet.setColumnWidth(13,9*256);
sheet.setColumnWidth(14,14*256);
sheet.setColumnWidth(15,59*256);
sheet.setColumnWidth(16,7*256);
sheet.setColumnWidth(17,11*256);
sheet.setColumnWidth(18,11*256);
sheet.setColumnWidth(19,11*256);
int rowNumber=0;
//向单元格里填充数据
for(int i=0;i<orders.size();i++){
List<OrderItem> orderItems=orderItemService.getMerByOrderId(orders.get(i));
for(int j=0; j<orderItems.size();j++){
row=sheet.createRow( 2+rowNumber);
row.setHeight((short)(20*20));
row.createCell(0).setCellValue(1+rowNumber);
row.createCell(1).setCellValue(orders.get(i).getSn());
row.createCell(2).setCellValue(orders.get(i).getCreatedDate().toString());
row.createCell(3).setCellValue(orders.get(i).getMember().getUsername());
if(orderItems.get(j).getName().equals("茅台集团天朝上品1箱")){
row.createCell(4).setCellValue("茅台集团天朝上品贵人酒");
row.createCell(5).setCellValue(1*orderItems.get(j).getQuantity());
}else if(orderItems.get(j).getName().equals("茅台集团天朝上品3箱")){
row.createCell(4).setCellValue("茅台集团天朝上品贵人酒");
row.createCell(5).setCellValue(3*orderItems.get(j).getQuantity());
}else if(orderItems.get(j).getName().equals("茅台集团天朝上品5箱")){
row.createCell(4).setCellValue("茅台集团天朝上品贵人酒");
row.createCell(5).setCellValue(5*orderItems.get(j).getQuantity());
}else if(orderItems.get(j).getName().equals("茅台集团天朝上品10箱")){
row.createCell(4).setCellValue("茅台集团天朝上品贵人酒");
row.createCell(5).setCellValue(10*orderItems.get(j).getQuantity());
}else{
row.createCell(4).setCellValue(orderItems.get(j).getName());
row.createCell(5).setCellValue(orderItems.get(j).getQuantity());
}
row.createCell(6).setCellValue(orderItems.get(j).getSku().getProduct().getUnit());
//规格
List<SpecificationValue> specificationValues = orderItems.get(j).getSku().getSpecificationValues();
if(!specificationValues.isEmpty()){
StringBuilder sb= new StringBuilder();
for(SpecificationValue specificationValue :specificationValues){
sb.append(" ").append(specificationValue.getValue());
}
row.createCell(7).setCellValue(sb.toString());
}else{
row.createCell(7).setCellValue("");
}
//商品分类
row.createCell(8).setCellValue(orderItems.get(j).getSku().getProduct().getProductCategory().getName());
//组合支付
Order.payType isExchangePoint = orderItems.get(j).getOrder().getIsExchangePoint();
if(isExchangePoint.ordinal()==2){
row.createCell(9).setCellValue("是");
}else{
row.createCell(9).setCellValue("否");
}
row.createCell(10).setCellValue(orders.get(i).getPrice().doubleValue());//人民币
String currencyCode = orders.get(i).getCurrency().getCurrencyCode();
if(!"CNY".equals(currencyCode)){
row.createCell(11).setCellValue(currencyCode);//积分类型
}
row.createCell(12).setCellValue(orders.get(i).getExchangePoint().doubleValue());//积分
row.createCell(13).setCellValue(orders.get(i).getConsignee());
row.createCell(14).setCellValue(orders.get(i).getPhone());
row.createCell(15).setCellValue(orders.get(i).getAreaName()+orders.get(i).getAddress());
row.createCell(16).setCellValue(orders.get(i).getZipCode());
row.createCell(17).setCellValue(getStart(orders.get(i).getStatus().toString()));
rowNumber++;
}
}
workbook.write(os);
} catch (IOException e) {
e.printStackTrace();
}
byte[] content = os.toByteArray();
return content;
}