Excel文件的讀取和生成(Java)

添加依賴

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

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>3.9</version>
</dependency>

檢查文件類型

public static void checkFile(MultipartFile file) throws IOException{
    	if(null == file){
    		throw new FileNotFoundException("文件不存在!");
    	}
    	String fileName = file.getOriginalFilename();
    	if(!fileName.endsWith("xls") && !fileName.endsWith("xlsx")){
    		throw new IOException(fileName + "不是excel文件");
    	}
}

獲得工作簿(Workbook)

    public static Workbook getWorkBook(MultipartFile file) {
    	String fileName = file.getOriginalFilename();
		Workbook workbook = null;//創建Workbook工作薄對象,表示整個excel
		try {
			InputStream is = file.getInputStream();
			//根據文件後綴名不同(xls和xlsx)獲得不同的Workbook實現類對象
			if(fileName.endsWith("xls")){
				workbook = new HSSFWorkbook(is);//2003
			}else if(fileName.endsWith("xlsx")){
				workbook = new XSSFWorkbook(is);//2007
			}
		} catch (IOException e) {
			System.out.println(e.getMessage());
		}
		return workbook;
	}

獲得單元格的字符串值

public static String getCellValue(Cell cell){
		String cellValue = "";
		if(cell == null){
			return cellValue;
		}
		if(cell.getCellType() == Cell.CELL_TYPE_NUMERIC){//把數字當成String來讀,避免出現1讀成1.0的情況
			cell.setCellType(Cell.CELL_TYPE_STRING);
		}
		//判斷數據的類型
        switch (cell.getCellType()){
	        case Cell.CELL_TYPE_NUMERIC: //數字
	            cellValue = String.valueOf(cell.getNumericCellValue());
	            break;
	        case Cell.CELL_TYPE_STRING: //字符串
	            cellValue = String.valueOf(cell.getStringCellValue());
	            break;
	        case Cell.CELL_TYPE_BOOLEAN: //Boolean
	            cellValue = String.valueOf(cell.getBooleanCellValue());
	            break;
	        case Cell.CELL_TYPE_FORMULA: //公式
	            cellValue = String.valueOf(cell.getCellFormula());
	            break;
	        case Cell.CELL_TYPE_BLANK: //空值 
	            cellValue = "";
	            break;
	        case Cell.CELL_TYPE_ERROR: //故障
	            cellValue = "非法字符";
	            break;
	        default:
	            cellValue = "未知類型";
	            break;
        }
		return cellValue;
	}

由整個excell轉化爲List<String[]>

public static List<String[]> readExcel(MultipartFile files) throws IOException {
        //檢查文件
        checkFile(files);
        //獲得Workbook工作薄對象
        Workbook workbook = getWorkBook(files);
        //創建返回對象,把每行中的值作爲一個數組,所有行作爲一個集合返回
        List<String[]> list = new ArrayList<>();
        if (workbook != null) {
            for (int sheetNum = 0; sheetNum < workbook.getNumberOfSheets(); sheetNum++) {
                //獲得當前sheet工作表
                Sheet sheet = workbook.getSheetAt(sheetNum);
                if (sheet == null) {
                    continue;
                }
                //獲得當前sheet的開始行
                int firstRowNum = sheet.getFirstRowNum();
                //獲得當前sheet的結束行
                int lastRowNum = sheet.getLastRowNum();
                //循環除了第一行的所有行
                for (int rowNum = firstRowNum + 1; rowNum <= lastRowNum; rowNum++) {
                    //獲得當前行
                    Row row = sheet.getRow(rowNum);
                    if (row == null || row.getPhysicalNumberOfCells() == 0) {
                        continue;
                    }
                    //獲得當前行的開始列
                    int firstCellNum = row.getFirstCellNum();
                    //獲得當前行的結束列
                    int lastCellNum = row.getLastCellNum();
                    String[] cells = new String[lastCellNum];
                    //循環當前行
                    for (int cellNum = firstCellNum; cellNum < lastCellNum; cellNum++) {
                        Cell cell = row.getCell(cellNum);
                        if (null == cell){
                            cells[cellNum] = "";
                            continue;
                        }
                        String guarantee_date = "";
                        //判斷是否爲日期類型
                        if (0 == cell.getCellType()) {
                            if (DateUtil.isCellDateFormatted(cell)) {
                                //用於轉化爲日期格式
                                Date d = cell.getDateCellValue();
                                DateFormat formater = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
                                guarantee_date = formater.format(d);
                                cells[cellNum] = guarantee_date;
                            } else {
                                int num = (int) cell.getNumericCellValue();
                                cells[cellNum] = String.valueOf(num);
                            }
                        } else {
                            cells[cellNum] = getCellValue(cell);
                        }
                    }
                    list.add(cells);
                }
            }
        }

        return list;
    }

如果讀取到的日期爲數字的話,使用下面方法轉化

    private Date getDateFromExcelNumber(String number) {
        Calendar calendar = new GregorianCalendar(1900, 0, -1);
        Date d = calendar.getTime();
        return DateUtils.addDays(d, Integer.valueOf(number));
    }

 

以上是讀取excel文件的,下面是生成excel文件!

創建工作簿

XSSFWorkbook workbook = new XSSFWorkbook();//2007

創建sheet頁

XSSFSheet sheet = workbook.createSheet("sheet頁的名稱");

單元格屬性設置

CellStyle cellStyle = workbook.createCellStyle();
cellStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER); // 居中
cellStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);// 上下居中
cellStyle.setBorderBottom(XSSFCellStyle.BORDER_THIN); //下邊框
cellStyle.setBorderLeft(XSSFCellStyle.BORDER_THIN);//左邊框
cellStyle.setBorderTop(XSSFCellStyle.BORDER_THIN);//上邊框
cellStyle.setBorderRight(XSSFCellStyle.BORDER_THIN);//右邊框
cellStale.setWrapText(true);//設置自動換行
cellStyle.setFillForegroundColor(IndexedColors.LIGHT_GREEN.getIndex());//背景色
cellStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);//填充背景色

XSSFFont font= workbook.createFont();
font.setFontName("Calibri");
font.setFontHeightInPoints((short) 10);//設置字體大小
font.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);//粗體顯示
cellStyle.setFont(font);//選擇需要用到的字體格式

時間類型的數據格式設置

cellStyle.setDataFormat(
workbook.getCreationHelper().createDataFormat().getFormat("yyyy/mm/dd")
);

設置列寬

sheet.setDefaultColumnWidth((short) 12);// 設置表格默認列寬度爲10個字節
sheet.setColumnWidth(0, 6*256);// 第一列設置6個字節寬度

新建一行,設置行高

XSSFRow row = sheet.createRow(0);//第一行,一般是標題行,需要單獨的樣式
row.setHeight((short) (40*15.625));

設置標題行文字和樣式(其餘行以此類推)

String[] headers = {"序號","標題列1","標題列2","標題列3","標題列4","標題列5", "標題列6"};
for (short i = 0; i < headers.length; i++) {
		XSSFCell cell = row.createCell(i);//新建單元格
		XSSFRichTextString text = new XSSFRichTextString(headers[i]);
		cell.setCellValue(text);//設置文本
		cell.setCellStyle(titleStyle);//設置樣式
}

保存文件

String filePath = "路徑和文件名.xlsx";
FileOutputStream fileOutputStream = new FileOutputStream(filePath);//指定路徑與名字和格式
workbook.write(fileOutputStream);//將數據寫出去
fileOutputStream.close();//關閉輸出流

下載文件到客戶端

參考自:https://blog.csdn.net/fengchao2016/article/details/55188805

https://blog.csdn.net/wanghaoqian/article/details/78284654

private static void downloadFile(File file, HttpServletRequest request,HttpServletResponse response) {
        String fileName = "中文.xlsx";
        InputStream fin = null;
        ServletOutputStream out = null;
        try {
            fin = new FileInputStream(file);
            out = response.getOutputStream();
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/octet-stream");
            boolean isMSIE = isMSBrowser(request);
            if (isMSIE) {
                //IE瀏覽器的亂碼問題解決
                fileName = URLEncoder.encode(fileName, "UTF-8");
            } else {
                //萬能亂碼問題解決
                fileName = new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
            }
            response.setHeader("Content-disposition", "attachment;filename=\"" + fileName + "\"");

            byte[] buffer = new byte[1024];
            int bytesToRead = -1;
            // 通過循環將讀入的Word文件的內容輸出到瀏覽器中
            while((bytesToRead = fin.read(buffer)) != -1) {
                out.write(buffer, 0, bytesToRead);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(fin != null) {
                try {
                    fin.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }

    private static String[] IEBrowserSignals = {"MSIE", "Trident", "Edge"};
    private static boolean isMSBrowser(HttpServletRequest request) {
        String userAgent = request.getHeader("User-Agent");
        for (String signal : IEBrowserSignals) {
            if (userAgent.contains(signal))
                return true;
        }
        return false;
    }

覺得有用的老鐵給個雙擊!

發佈了86 篇原創文章 · 獲贊 144 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章