Excle导入导出操作代码

 博客原文 ----> https://www.yanzhaochang.top/read/25

文件导入操作

   Workbook wb = new HSSFWorkbook();
   String headers[] = { "用户名", "密码", "姓名" };
   //模拟数据
   List list = new List();
   for(int i=0;i<10;i++){
      User user = new User("u_usercode","u_password","u_username");   
      list.add(user);
   }
   // 写入数据
   ExcelUtil.fillUserExcelData(list, wb, headers);
   // 写入浏览器
   ResponseUtil.export(response, wb, "用户信息列表.xls");

文件导出操作

    Workbook wb = ExcelUtil.DownWithTemplate("用户信息模板.xls");
    ResponseUtil.export(response, wb, "用户信息模板.xls");

ExcelUtil工具类

import com.qidian.domain.User;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFCell;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class ExcelUtil {
   //制作用户excel头部
    private static void fillHeader(String[] headers, Sheet sheet, Row row, CellStyle cellStyle) {
	for (int i = 0; i < headers.length; i++) {
	    Cell cell = row.createCell(i);
    	    cell.setCellValue(headers[i]);
	    cell.setCellStyle(cellStyle);
	    int length = headers[i].getBytes().length;
	    sheet.setColumnWidth((short) i, (short) (length * 256));
	}
    }

    // 制作用户的excel内容
    public static void fillUserExcelData(List list, Workbook wb, String[] headers) {
	int rowIndex = 0;
	Sheet sheet = wb.createSheet("用户信息");
	Row row = sheet.createRow(rowIndex++);
	// 居中样式
	CellStyle cellStyle = wb.createCellStyle();
	// 居中
	cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
	cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
	// 设置标题的值
	fillHeader(headers, sheet, row, cellStyle);
	for (User user : list) {
	    row = sheet.createRow(rowIndex++);
	    Cell cell = row.createCell(0);
	    if (cell.toString() != null && cell.toString().equals("")) {
		// 填充数据
		fillUserExcel(row, cellStyle, user, cell);
	    }
	}
	// 设置自动调整列宽中文支持
	setSizeColumn(sheet, headers.length);
    }

    // 设置用户的值
    private static void fillUserExcel(Row row, CellStyle cellStyle, User user, Cell cell) {
	if (user.getU_usercode() != null) {
	    cell.setCellValue(user.getU_usercode());
	    cell.setCellStyle(cellStyle);
	}
	cell = row.createCell(1);
	if (user.getU_username() != null) {
	    cell.setCellValue(user.getU_username());
	    cell.setCellStyle(cellStyle);
	}
	cell = row.createCell(2);
	if (user.getU_passWord() != null) {
	    cell.setCellValue(user.getU_passWord());
	    cell.setCellStyle(cellStyle);
	}
    }

    // 设置自动调整列宽中文支持
    private static void setSizeColumn(Sheet sheet, int size) {
	for (int columnNum = 0; columnNum < size; columnNum++) {
	    int columnWidth = sheet.getColumnWidth(columnNum) / 256;
	    for (int rowNum = 0; rowNum < sheet.getLastRowNum(); rowNum++) {
	    	Row currentRow;
	    	// 当前行未被使用过
		if (sheet.getRow(rowNum) == null) {
        	    currentRow = sheet.createRow(rowNum);
		} else {
		    currentRow = sheet.getRow(rowNum);
		}
		if (currentRow.getCell(columnNum) != null) {
		    Cell currentCell = currentRow.getCell(columnNum);
		    if (currentCell.getCellType() == XSSFCell.CELL_TYPE_STRING) {
			int length = currentCell.getStringCellValue().getBytes().length;
	        	if (columnWidth < length) {
			    columnWidth = length;
			}
		    }
		}
	    }
	sheet.setColumnWidth(columnNum, columnWidth * 256);
        }
    };
}

ResponseUtil工具类

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.Workbook;

public class ResponseUtil {
    public static void export(HttpServletResponse response, Workbook wb, String filename) {
        try {
	    ByteArrayOutputStream os = new ByteArrayOutputStream();
	    wb.write(os);
	    byte[] content = os.toByteArray();
    	    InputStream is = new ByteArrayInputStream(content);
	    // 设置response参数,可以打开下载页面
	    response.reset();
	    response.setHeader("Content-Disposition","attachment; filename=" + new String(filename.getBytes("utf-8"), "ISO-8859-1"));
	    response.setContentType("application/vnd.ms-excel;charset=utf-8");
	    ServletOutputStream out = response.getOutputStream();
	    BufferedInputStream bis = null;
	    BufferedOutputStream bos = null;
	    try {
	    	bis = new BufferedInputStream(is);
		bos = new BufferedOutputStream(out);
		byte[] buff = new byte[2048];
		int bytesRead;
		while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
		    bos.write(buff, 0, bytesRead);
		}
	    } catch (Exception e) {
		e.printStackTrace();
	    } finally {
		if (bis != null)
		    bis.close();
		if (bos != null)
		bos.close();
	    }
        } catch (Exception e) {
	    e.printStackTrace();
	}
    };
}

 

你可能感兴趣的:(Java)