1. 程式人生 > >匯入/匯出Excel利用apache.poi

匯入/匯出Excel利用apache.poi

一、生成Excel

1、匯入jar包


maven地址

       <dependency>  
            <groupId>org.apache.poi</groupId>  
            <artifactId>poi</artifactId>  
            <version>3.16</version>  
        </dependency>  


2、編寫ExcelUtil工具類

package com.qn.yun.utils;

import org.apache.poi.hssf.util.HSSFColor.HSSFColorPredefined;
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.FillPatternType;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
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;

public class ExcelUtil {

	private Workbook wb = null;

	private Sheet sheet = null;

	public ExcelUtil(Workbook wb, Sheet sheet) {
		super();
		this.wb = wb;
		this.sheet = sheet;
	}

	/**
	 * 設定表頭樣式
	 * 
	 * @return
	 */
	public CellStyle getHeadStyle() {
		// 建立單元格樣式
		CellStyle cellStyle = wb.createCellStyle();
		// 設定單元格的背景顏色為淡藍色
		cellStyle.setFillForegroundColor(HSSFColorPredefined.LIGHT_YELLOW.getIndex());
		cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
		// 設定單元格居中對齊
		cellStyle.setAlignment(HorizontalAlignment.CENTER);
		// 設定單元格垂直居中對齊
		cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
		// 建立單元格內容顯示不下時自動換行
		cellStyle.setWrapText(true);
		// 設定單元格字型樣式
		Font font = wb.createFont();
		// 設定字型加粗
		font.setBold(true);
		font.setFontName("宋體");
		font.setFontHeight((short) 200);
		cellStyle.setFont(font);
		// 設定單元格邊框為細線條
		cellStyle.setBorderLeft(BorderStyle.THIN);
		cellStyle.setBorderBottom(BorderStyle.THIN);
		cellStyle.setBorderRight(BorderStyle.THIN);
		cellStyle.setBorderTop(BorderStyle.THIN);
		return cellStyle;
	}

	public void buildTitle(Sheet sheet, String[] titles) {
		Row headRow = sheet.createRow(0);
		Cell cell = null;
		for (int i = 0; i < titles.length; i++) {
			cell = headRow.createCell(i);
			cell.setCellStyle(getHeadStyle());
			cell.setCellValue(titles[i]);
		}
	}

	/**
	 * 設定表體的單元格樣式
	 * 
	 * @return
	 */
	public CellStyle getBodyStyle() {
		// 建立單元格樣式
		CellStyle cellStyle = wb.createCellStyle();
		// 設定單元格居中對齊
		cellStyle.setAlignment(HorizontalAlignment.CENTER);
		// 設定單元格垂直居中對齊
		cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
		// 建立單元格內容顯示不下時自動換行
		cellStyle.setWrapText(true);
		// 設定單元格字型樣式
		Font font = wb.createFont();
		// 設定字型加粗
		font.setBold(true);
		font.setFontName("宋體");
		font.setFontHeight((short) 200);
		cellStyle.setFont(font);
		// 設定單元格邊框為細線條
		cellStyle.setBorderLeft(BorderStyle.THIN);
		cellStyle.setBorderBottom(BorderStyle.THIN);
		cellStyle.setBorderRight(BorderStyle.THIN);
		cellStyle.setBorderTop(BorderStyle.THIN);
		return cellStyle;
	}

	public void autoSizeColumnSize(Sheet sheet) {
		if (sheet == null) {
			return;
		}
		if (sheet.getRow(0) == null) {
			return;
		}
		int colCount = sheet.getRow(0).getPhysicalNumberOfCells();
		for (int column = 0; column < colCount; column++) {
			int columnWidth = sheet.getColumnWidth(column) / 256;
			for (int rowNum = 1; rowNum <= sheet.getLastRowNum(); rowNum++) {
				Row currentRow;
				if (sheet.getRow(rowNum) == null) {
					currentRow = sheet.createRow(rowNum);
				} else {
					currentRow = sheet.getRow(rowNum);
				}
				if (currentRow.getCell(column) != null) {
					Cell currentCell = currentRow.getCell(column);
					int length = currentCell.toString().length();
					if (columnWidth < length) {
						columnWidth = length;
					}
				}
			}
			sheet.setColumnWidth(column, (columnWidth * 2) * 256);
		}
	}
}

3、編寫資料內容service
package com.qn.demo;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.junit.Test;

import com.qn.yun.utils.ExcelUtil;

public class ExcelYunDemo {

	@Test
	public void outputExcel(){
		SXSSFWorkbook workbook = new SXSSFWorkbook(100);
		Sheet sheet = workbook.createSheet("學生內容表");
		ExcelUtil excelUtil = new ExcelUtil(workbook, sheet);
		//設計單元格樣式
		CellStyle bodyStyle = excelUtil.getBodyStyle();
		
		// 構建表頭
		String[] titles={"姓名","性別","年齡"};
		excelUtil.buildTitle(sheet, titles);
		
		Row bodyRow=sheet.createRow(1);
		Cell cell=bodyRow.createCell(0);
		cell.setCellValue("小明");
		cell=bodyRow.createCell(1);
		cell.setCellValue("男");
		cell=bodyRow.createCell(2);
		cell.setCellValue(12);
		
		excelUtil.autoSizeColumnSize(sheet);
		ByteArrayOutputStream out=new ByteArrayOutputStream();
		try {
			workbook.write(out);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.err.println("匯出失敗");
		}finally{
			try {
				out.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				System.err.println("關閉流失敗");
			}
		}
		workbook.dispose();
		byte[] byteArray = out.toByteArray();
		OutputStream outputStream=null;
		try {
			outputStream=new FileOutputStream(new File("f://學生資訊.xlsx"));
			outputStream.write(byteArray);
			System.out.println("輸出ok");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.err.println("輸出失敗");
		}finally {
			try {
				outputStream.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}

4、匯出的表格中要合併單元格

/** 
 *  
 * @Project:Report 
 * @Title:MergeCell.java 
 * @Package:com.you.excel 
 * @Description: 
 * @Author:YouHaiDong 
 * @Date:2015年11月4日 下午2:36:46 
 * @Version: 
 */  
package com.you.excel;  
  
import java.io.FileOutputStream;  
  
import org.apache.poi.hssf.usermodel.HSSFCell;  
import org.apache.poi.hssf.usermodel.HSSFRichTextString;  
import org.apache.poi.hssf.usermodel.HSSFRow;  
import org.apache.poi.hssf.usermodel.HSSFSheet;  
import org.apache.poi.hssf.usermodel.HSSFWorkbook;  
import org.apache.poi.hssf.util.Region;  
  
/** 
 * <p>合併單元格</p> 
 * @ClassName:MergeCell 
 * @Description: 
 * @Author:YouHaiDong 
 * @Date:2015年11月4日 下午2:36:46 
 *  
 */  
public class MergeCell   
{  
    /** 
     * 合併單元格 
     * @Title:MergeCell 
     * @Description: 
     * @param args 
     * @Date:2015年11月4日 下午2:36:46 
     * @return: void  
     * @throws Exception 
     */  
    @SuppressWarnings({ "resource", "deprecation" })  
    public static void main(String[] args) throws Exception   
    {  
        //建立workbook   
        HSSFWorkbook workbook = new HSSFWorkbook();   
        //建立sheet頁  
        HSSFSheet sheet = workbook.createSheet("學生表");   
        //建立單元格  
        HSSFRow row = sheet.createRow(0);   
        HSSFCell c0 = row.createCell(0);   
        c0.setCellValue(new HSSFRichTextString("學號"));   
        HSSFCell c1 = row.createCell(1);   
        c1.setCellValue(new HSSFRichTextString("姓名"));   
        HSSFCell c2 = row.createCell(2);   
        c2.setCellValue(new HSSFRichTextString("性別"));   
        HSSFCell c3 = row.createCell(3);   
        c3.setCellValue(new HSSFRichTextString("年齡"));   
        HSSFCell c4 = row.createCell(4);   
        c4.setCellValue(new HSSFRichTextString("2015年分數"));   
        HSSFCell c5 = row.createCell(7);   
        c5.setCellValue(new HSSFRichTextString("2014年分數"));   
        HSSFRow row1 = sheet.createRow(1);   
        HSSFCell c6 = row1.createCell(4);   
        c6.setCellValue(new HSSFRichTextString("語文"));   
        HSSFCell c7 = row1.createCell(5);   
        c7.setCellValue(new HSSFRichTextString("數學"));   
        HSSFCell c8 = row1.createCell(6);   
        c8.setCellValue(new HSSFRichTextString("外語"));  
        HSSFCell c9 = row1.createCell(7);   
        c9.setCellValue(new HSSFRichTextString("語文"));   
        HSSFCell c10 = row1.createCell(8);   
        c10.setCellValue(new HSSFRichTextString("數學"));   
        HSSFCell c11 = row1.createCell(9);   
        c11.setCellValue(new HSSFRichTextString("外語"));  
          
        Region region1 = new Region(0, (short)0, 1, (short)0);   
        Region region2 = new Region(0, (short)1, 1, (short)1);   
        Region region3 = new Region(0, (short)2, 1, (short)2);   
        Region region4 = new Region(0, (short)3, 1, (short)3);   
        Region region5 = new Region(0, (short)4, 0, (short)6);   
        Region region6 = new Region(0, (short)7, 0, (short)9);   
        sheet.addMergedRegion(region1);   
        sheet.addMergedRegion(region2);   
        sheet.addMergedRegion(region3);   
        sheet.addMergedRegion(region4);   
        sheet.addMergedRegion(region5);   
        sheet.addMergedRegion(region6);   
  
//此方法在POI3.8中已經被廢棄,建議使用下面一個    
或者用  
  
  
CellRangeAddress region1 = new CellRangeAddress(rowNumber, rowNumber, (short) 0, (short) 11);     
  
  
//引數1:起始行 引數2:終止行 引數3:起始列 引數4:終止列      
但應注意兩個構造方法的引數不是一樣的,具體使用哪個取決於POI的不同版本。   
  
  
sheet.addMergedRegion(region1);   

FileOutputStream stream = new FileOutputStream("d:/student.xls"); workbook.write(stream); } } 實現之後為:

5、實際工程中,要用controller寫入介面Spring-core
	/**
	 * 匯出憑證列表
	 * 
	 */
	@PostMapping("/exportVoucher")
	public void exportVoucher(@RequestBody VouQueryVO vouQueryVO) {
		response.setContentType("application/vnd.ms-excel");
		String fileName = "憑證列表";
		try {
			response.setCharacterEncoding("UTF-8");
			fileName = URLEncoder.encode(fileName, "UTF-8");
			response.setHeader("Content-disposition", "attachment; filename=" + fileName + ".xlsx");// 組裝附件名稱和格式
			// byte[] bytes = new byte[1024];
			byte[] bytes = bsVoucherService.exportVoucherList(vouQueryVO);
			response.getOutputStream().write(bytes);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

6、設定單元格可以用以下方法

建立sheet什麼的就不多說了,直接進入正題  
  
  
HSSFCellStyle cellStyle = wb.createCellStyle();    
 一、設定背景色:  
  
  
cellStyle.setFillForegroundColor((short) 13);// 設定背景色    
cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);    
二、設定邊框:  
  
  
cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN); //下邊框    
cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);//左邊框    
cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);//上邊框    
cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);//右邊框    
三、設定居中:  
  
  
cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 居中    
四、設定字型:  
  
  
HSSFFont font = wb.createFont();    
font.setFontName("黑體");    
font.setFontHeightInPoints((short) 16);//設定字型大小    
    
HSSFFont font2 = wb.createFont();    
font2.setFontName("仿宋_GB2312");    
font2.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);//粗體顯示    
font2.setFontHeightInPoints((short) 12);    
    
cellStyle.setFont(font);//選擇需要用到的字型格式    
五、設定列寬:  
  
sheet.setColumnWidth(0, 3766);   
//第一個引數代表列id(從0開始),第2個引數代表寬度值  參考 :"2012-08-10"的寬度為2500    
六、設定自動換行:  
  
cellStyle.setWrapText(true);//設定自動換行    
七、合併單元格:  
  
Region region1 = new Region(0, (short) 0, 0, (short) 6);//引數1:行號 引數2:起始列號 引數3:行號 引數4:終止列號    
  
  
//此方法在POI3.8中已經被廢棄,建議使用下面一個    
或者用  
  
  
CellRangeAddress region1 = new CellRangeAddress(rowNumber, rowNumber, (short) 0, (short) 11);     
  
  
//引數1:起始行 引數2:終止行 引數3:起始列 引數4:終止列      
但應注意兩個構造方法的引數不是一樣的,具體使用哪個取決於POI的不同版本。   
  
  
sheet.addMergedRegion(region1);    


二、讀取Excel表格

1、controller介面

	@PostMapping("/inputExcel")
	public String inputExcel(@RequestParam(value = "uploadFile", required = true) MultipartFile uploadFile){
		return excelService.uplodeExcelService(uploadFile);
	}

2、service層
	public String uplodeExcelService(MultipartFile uploadFile){
		String msg="";
		if(uploadFile==null)
		  return 	msg="上傳檔案為空";
		if(uploadFile.getSize()>1024*1024*10)//單位為位元組
			return msg="上傳的檔案大於10M";
		// 1.xls型別的為:application/vnd.ms-excel
		// 2、xlsx的型別為:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
		String contentType = uploadFile.getContentType();
		if(!"application/vnd.ms-excel".equals(contentType))
			return msg="上傳的檔案不是已xls結尾的Excel檔案";
		Workbook workbook=null;
		try {
			workbook=new HSSFWorkbook(uploadFile.getInputStream());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return msg="上傳失敗1";
		}
		Sheet sheet = workbook.getSheetAt(0);
		
		List<User> userList=new ArrayList<User>();
		int lastRowNum = sheet.getLastRowNum();
		for(int startRowNum=2;startRowNum<=lastRowNum;startRowNum++){
			User user = new User();
			Row row = sheet.getRow(startRowNum);
			if(row==null) 
				continue;
			short lastCellNum = row.getLastCellNum();
			for(int cellNum=0;cellNum<=lastCellNum;cellNum++){
				Cell cell = row.getCell(cellNum);
				String value="";
				if(cell!=null&&cell.getCellType()!=HSSFCell.CELL_TYPE_BLANK&&cell.getCellType()!=HSSFCell.CELL_TYPE_ERROR){
					switch (cell.getCellType()) {
					// 數字
					case HSSFCell.CELL_TYPE_NUMERIC:// 數字
						// 處理日期格式、時間格式
						if(HSSFDateUtil.isCellDateFormatted(cell)){
							Date date = cell.getDateCellValue();
							value = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
						}else{
							value = NumberToTextConverter.toText(cell.getNumericCellValue());
						}
						break;
						// 字串
					 case HSSFCell.CELL_TYPE_STRING:
					 value=cell.getStringCellValue();
					 // 公式
					 case HSSFCell.CELL_TYPE_FORMULA:
						 try {
							 DecimalFormat df = new DecimalFormat("0.00");//設定小數點的位數
							 value = String.valueOf(df.format(cell.getNumericCellValue()));
						} catch (Exception e) {
							value = String.valueOf(cell.getRichStringCellValue());
						}
						
					}
				}
				if(!"".equals(value)){
					switch (cellNum) {
					case 0:
						user.setName(value);
						break;
					case 1:
						user.setAge((int)Double.parseDouble(value));
						break;
					case 2:
						user.setPassword(value);
						break;
					}
				}
			}
			userList.add(user);
		}
		System.out.println(userList);
		return msg="上傳成功";
	}