xssf導入excel

Java用XSSFWorkbook實現excel簡單讀寫
一、概述
二、所需的jar
三、XSSFWorkbook的使用方法
四、源代碼
一、概述
Apache POI是 Java 程序員用來處理 MS Office 文件的常用開源庫。由 Apache 軟件基金會開發,使用 Java 分佈式設計或修改 Microsoft Office 文件,包含一系列類和方法對用戶輸入數據或文件進行編碼和解碼。其中 POI-HSSF 和 POI-XSSF 是用來處理 excel 文件的組件,前者對應 97~2007版本的文件格式(.xls), 後者對應07以後的格式(.xlsx),更多關於 POI 的介紹請訪問官方主頁。
個人覺得 POI 對 office 的對象進行了很好的抽象設計,因此學習起來比較平滑。在閱讀學習的同時打開excel進行同步操作,你會感覺到使用 POI 和使用 office 一樣簡單。

二、所需的jar
進行操作之前,先用maven等工具導入依賴包,或者手動下載jar導入classpath

org.apache.poi 3.14

三、XSSFWorkbook的使用方法
// 07之前版本
Workbook wb = new HSSFWorkbook();
FileOutputStream fileOut = new FileOutputStream(“workbook.xls”);
wb.write(fileOut);
fileOut.close();
// 07之後版本 Workbook wb = new XSSFWorkbook();
FileOutputStream fileOut = new FileOutputStream(“workbook.xlsx”);
wb.write(fileOut);
fileOut.close();

**注:我用的是07之後版本 **

// wb 可以是上述創建的兩個對象之一
Sheet sheet = wb.createSheet(); Sheet sheet =
wb.createSheet(“庫存”);

// 1. 首先創建行,聲明行的索引,從0開始。
Row row = sheet.createRow(0);

四、源代碼
實體類:

private int index;
private String name;
private String age;
private String brithday;

public ExcelInfo() {
}

public ExcelInfo(int index, String name, String age, String brithday) {
	this.index = index;
	this.name = name;
	this.age = age;
	this.brithday = brithday;
}
//省略get/set方法

@Override
public String toString() {
	return "第" + index + "行的數據如:姓名:" + name + ",年齡:" + age + ",生日:" + brithday ;
}

導出Excel類:

public static void main(String[] args) {

	List<ExcelInfo> list = new ArrayList<ExcelInfo>();
	list.add(new ExcelInfo(1, "石頭", "24", "6/12"));
	list.add(new ExcelInfo(2, "火男", "25", "6/13"));
	list.add(new ExcelInfo(3, "火女", "26", "6/14"));
	list.add(new ExcelInfo(4, "武器", "27", "6/15"));
	list.add(new ExcelInfo(5, "提莫", "28", "6/16"));
	excelExp("D:\\eclipse-project\\javaweb\\AccessTest\\excel\\result.xlsx", list);
}

public static void excelExp(String filePath, List<ExcelInfo> list) {
	Workbook wb = null;
	OutputStream out = null;
	try {
		wb = new XSSFWorkbook();
		Sheet sheet = wb.createSheet("聯繫表"); //重命名sheet1的工作表名
		Row r = sheet.createRow(0);			//0 表示 第一行
		r.createCell(0).setCellValue("姓名");
		r.createCell(1).setCellValue("年齡");
		r.createCell(2).setCellValue("生日");	//給表頭定義字段名

		for (ExcelInfo user : list) {
			r = sheet.createRow(user.getIndex()); //按照對象的index對應第幾行
			r.createCell(0).setCellValue(user.getName());
			r.createCell(1).setCellValue(user.getAge());
			r.createCell(2).setCellValue(user.getDate());
		}
		out = new FileOutputStream(filePath); // 字節輸出流
		wb.write(out); //導出excel
	} catch (Exception e) {
		e.printStackTrace();
	} finally {
		try {
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

準備被讀入的excel內容如下:

控制檯輸出如下圖:

注:輸出形式是根據toString()形式輸出,可以改爲自己喜歡的方式,請修改實體類中的toString()。

讀入類

public static void main(String[] args) throws IOException {
List list = importExcel(“D:\eclipse-project\javaweb\AccessTest\excel\test.xlsx”);
for (ExcelInfo excelInfo : list) {
System.out.println(excelInfo);
}
}

public static List<ExcelInfo> importExcel(String file) throws IOException {
	FileInputStream in = null;
	List<ExcelInfo> result = null;
	try {
		in = new FileInputStream(file);
		result = new ArrayList<ExcelInfo>();
		Workbook wb = new XSSFWorkbook(in); //基於文件字節輸入流 創建工作簿對象
		Sheet sheet = wb.getSheetAt(0); // sheetIndex 表示 第一個工作表
		for (Row row : sheet) {
			if (row.getRowNum() < 1) {	//因爲第一行是一些字段名,此行不獲取字符串
				continue;
			}
			String cellValue = new String(); //用來賦值,取格式化後的日期字符串
			ExcelInfo eInfo = new ExcelInfo();
			eInfo.setIndex(row.getRowNum());
			eInfo.setName(row.getCell(0).getStringCellValue());	//獲取第一列單元表格的數據值
			row.getCell(1).setCellType(Cell.CELL_TYPE_STRING); //因爲年齡的數據值是一個數值,所以需要進行轉字符串,否則報異常
			eInfo.setAge(row.getCell(1).getStringCellValue());
			SimpleDateFormat formatter = new SimpleDateFormat("MM-dd");	//定義時間格式化對象
			Date dateCell = row.getCell(2).getDateCellValue(); // 
			cellValue = formatter.format(dateCell);//進行日期格式化
			eInfo.setBrithday(cellValue);
			result.add(eInfo);
		}

		wb.close();
	} catch (Exception e) {
		e.printStackTrace();
	} finally {
		in.close();
	}
	return result;
}

導出的excel內容如下圖
在這裏插入圖片描述

補充:
如果你是用request 接收,寫法如下:

// 轉換request,解析出request中的文件
	MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;

	// 獲取文件map集合
	Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
      MultipartFile   file = entity.getValue();
      // 創建workbook
      XSSFWorkbook wb = new XSSFWorkbook(file.getInputStream());
     Sheet xssfSheet = wb.get(0);
         //循環取每行的數據
    for (int rowIndex = 1; rowIndex < xssfSheet.getPhysicalNumberOfRows(); rowIndex++) {
        XSSFRow xssfRow = xssfSheet.getRow(rowIndex);
        if (xssfRow == null) {
            continue;
        }


        //循環取每個單元格(cell)的數據
        for (int cellIndex = 0; cellIndex < xssfRow.getPhysicalNumberOfCells();     cellIndex++) {
           
        }
        
       //   這裏說下獲取不同類型的值:
             ① 獲取String 類型
             cell.setCellType(Cell.CELL_TYPE_STRING);
             String  a = cell.getStringCellValue();
             ② 獲取 日期類型,實體類爲Date類型,要求格式yyyy-MM-dd
            double value = cell.getNumericCellValue();
            if(0.0!=value){
                Date d = org.apache.poi.ss.usermodel.DateUtil.getJavaDate(value);
                SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
                String dateStr =  f.format(d);
                Date  date  =  sdf.parse(dateStr);
                
            }
            ③ 獲取BigDecimal類型
         cell.setCellType(Cell.CELL_TYPE_STRING);
         new BigDecimal(cell.getStringCellValue());    
    }
  
}

原文鏈接:https://blog.csdn.net/qq_35525955/article/details/80904844

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章