Java讀寫Excel,附DecimalFormat數字格式用法

1、導入相關依賴

maven依賴

<!-- excel讀取 -->
<dependency>
	<groupId>org.apache.poi</groupId>
	<artifactId>poi</artifactId>
	<version>4.1.0</version>
</dependency>
<dependency>
	<groupId>org.apache.poi</groupId>
	<artifactId>poi-ooxml-schemas</artifactId>
	<version>4.1.0</version>
</dependency>
<dependency>
	<groupId>org.apache.poi</groupId>
	<artifactId>poi-ooxml</artifactId>
	<version>4.1.0</version>
</dependency>

2、編寫ReadExcel.java

package com.hx.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

/**
 * @author Huathy
 * @time 2020年3月27日  上午10:49:21
 */
@SuppressWarnings("resource")
public class ReadExcel {
	private DecimalFormat df = new DecimalFormat("0.00");	
	// 將double類型的值小數位保留2位
	
	/**
	 * 通過文件方式,將一個Excel中的數據讀取到一個集合中
	 * @param file
	 * @return
	 * @throws IOException
	 * @throws FileNotFoundException
	 */
	public List<Map<String, String>> importExcel(File fl) throws FileNotFoundException, IOException {
		List<Map<String, String>> list = new ArrayList<Map<String, String>>();
		// 創建一個excel對象
		Workbook workbook = null;

		String fileName = fl.getName().toLowerCase(); // 獲取文件名
		if (fileName.endsWith("xls")) {
			workbook = new HSSFWorkbook(new FileInputStream(fl));
		} else if (fileName.endsWith("xlsx")) {
			workbook = new XSSFWorkbook(new FileInputStream(fl));
		} else {
			throw new RuntimeException("選擇的文件不是Excel格式文件...");
		}

		// 獲取excel中的Sheet1表(即默認的第一張表)
		Sheet sheet = workbook.getSheet("Sheet1");
		int rows = sheet.getLastRowNum(); // 獲取表格的最後一行編號
		if (rows <= 0) { // 如果小於0,則表示表格中沒有數據。
			throw new RuntimeException("表格中沒有數據...");
		}
		// 循環讀取每一行數據
		Row row = null;
		Iterator<Cell> cols = null;
		Map<String, String> map = null;
		
		int index = 0; // 列
		for (int i = 0; i <= rows; i++) {	//從第一行開始讀
			index = 0;
			row = sheet.getRow(i);	//獲取這一行的列信息
			if (row == null) {
				continue;
			}
			cols = row.cellIterator(); // 獲取這一行中的所有列的信息
			map = new HashMap<String, String>();
			while (cols.hasNext()) {
				map.put("第"+String.valueOf(index+1)+"列", getCelltoString(cols.next()));	//cols.next()獲取單元格中的值
				index++;
			}
			list.add(map);
		}
		return list;
	}

	/**
	 * 通過流的方式讀取excel文件
	 * @param fileName
	 * @param is
	 * @return
	 * @throws IOException
	 */
	public List<Map<String,String>> importExcel(String fileName ,InputStream is) throws IOException{
		List<Map<String,String>> list = new ArrayList<Map<String,String>>();
		//創建一個excel對象
		Workbook workbook = null;

		fileName= fileName.toLowerCase();	//獲取文件名
		if(fileName.endsWith("xls")){
			workbook = new HSSFWorkbook(is);
		}else if(fileName.endsWith("xlsx")){
			workbook = new XSSFWorkbook(is);
		}else{
			throw new RuntimeException("選擇的文件不是Excel格式文件...");
		}
		
		//獲取excel中的一張表
		Sheet sheet = workbook.getSheet("Sheet1");
		int rows = sheet.getLastRowNum();	//獲取表格的最後一行編號
		if(rows <= 0){	//小於0,說明沒有數據
			throw new RuntimeException("表格中沒有數據...");
		}
		
		//循環讀取每一行數據
		Row row = null;
		Iterator<Cell> cols = null;
		Map<String,String> map = null;
		
		int index = 0;	//列
		for(int i=0; i<=rows; i++){	//從第一行開始讀取
			index = 0;
			row = sheet.getRow(i);
			if(row == null){
				continue;
			}
			cols = row.cellIterator();	//獲取這一行中的所有列
			map = new HashMap<String,String>();
			while( cols.hasNext() ){
				map.put("第"+String.valueOf(index+1)+"列", getCelltoString(cols.next()));
				index++;
			}
			list.add(map);
		}
		return list;
	}
	
	/**
	 * 將單元格中的數據轉成字符串返回
	 * 
	 * @param cell
	 * @return
	 */
	private String getCelltoString(Cell cell) {
		if (cell == null) {
			return "";
		}
		
		String str = "";
		switch (cell.getCellType()) {
		case STRING:	//string
			str = cell.getStringCellValue(); break;
		case NUMERIC:	//數值型,轉爲string
			str = String.valueOf(df.format(cell.getNumericCellValue())); break;
		case BOOLEAN:	//Boolean型
			str = String.valueOf(cell.getBooleanCellValue()); break;
		case FORMULA:	//公式
			str = String.valueOf(cell.getCellFormula()); break;
		case BLANK:		//空白
			str = ""; break;
		case ERROR:		//錯誤
			str = ""; break;
		default:
			str = "";
		}
		return str;
	}
}

3、編寫WriteExcel.java

package com.hx.util;

import java.io.FileOutputStream;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

/**
 * @author Huathy
 * @time 2020年3月27日  上午10:49:09
 */
public class WriteExcelXls {
	/**
	 * 
	 * @param path	文件保存路徑,僅支持xls格式
	 * @throws Exception 
	 */
	public void WriteXls(List<List<String>> lists,String path) throws Exception{
		if(lists.isEmpty()){
			throw new Exception("集合中沒有數據...");
		}
		String fileFormat = path.substring( path.lastIndexOf(".")+1 );
		
		//創建一下工作簿
		Workbook wb = null;
		if( "xls".equals(fileFormat) ){		//以xls格式結尾,創建HSSFWorkbook對象
			wb = new HSSFWorkbook();
		}else if( "xlsx".equals(fileFormat) ){	//以xls格式結尾,創建XSSFWorkbook對象
			wb = new XSSFWorkbook();
		}else {
			throw new Exception("文件保存格式錯誤...");
		}
		
		//創建Sheet1頁面
		Sheet sheet = wb.createSheet("Sheet1");

		List<String> rowData = null;
		//開始寫數據
		for(int i=0;i<lists.size();i++){
			//獲取每行的數據
			rowData = lists.get(i);
			//創建單元格,括號中的數字表示該行的第幾列,從0開始
			Row row = sheet.createRow(i);
			for(int j=0;j<rowData.size();j++){
				//創建單元格並賦值
				row.createCell(j).setCellValue(rowData.get(j));
			}
		}
		
		FileOutputStream fos = new FileOutputStream(path);
		wb.write(fos);
		fos.close();
		wb.close();
		System.out.println(path+" 文件寫成功!");
	}
}

4、編寫測試類,測試讀寫

package com.hx.ExcelWR;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.hx.util.ReadExcel;
import com.hx.util.WriteExcelXls;

/**
 * @author Huathy
 * @time 2020年3月27日  上午10:48:59
 */
public class App {
	public static void main(String[] args) {
		String path = "G:\\ExcelRW.xlsx";
		File file = new File(path);
		
		List<List<String>> temp = null;
		try {
			//讀取Excel文件測試
			ReadExcel re = new ReadExcel();
			List<Map<String, String>> list = re.importExcel(file);
			System.out.println(list); 
			
			//數據處理,由於我讀取數據是List<Map<String, String>>的,但寫的時候需要List<String>的參數。故需要對數據進行處理
			temp = new ArrayList<List<String>>();
			List<String> strs = null;
			Map<String,String> map = null;
			for(int i=0;i<list.size();i++){
				strs = new ArrayList<String>();
				map = list.get(i);
				for(int j=0;j<map.size();j++){
					strs.add(map.get("第"+(j+1)+"列"));
				}
				temp.add(strs);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		//測試寫Excel功能
		WriteExcelXls wex = new WriteExcelXls();
		try {
			wex.WriteXls(temp, "G:\\a.xls");	//測試xls格式
			wex.WriteXls(temp, "G:\\a.xlsx");	//測試xlsx格式
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

讀寫測試Excel表格及結果

在這裏插入圖片描述

附:DecimalFormat

DecimalFormat df = new DecimalFormat(“0”);

變量 含義
“0” //不保留小數
“0.0” 保留1位小數
“00.000” 2整數位,3小數位
“#” 取所有整數部分
“#.##%” 以百分比方式計數,並取2位小數
“#.##E0” 顯示爲科學計數法,並取2位小數
“,###” 每三位以逗號進行分隔
“第#列” //不保留小數
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章