利用Java生成excel,並且讀取excel中的內容

一、實現的效果

a、創建文件效果

b、讀取效果

二、需要的jar包

<dependency>
   <groupId>net.sourceforge.jexcelapi</groupId>
    <artifactId>jxl</artifactId>
    <version>2.6.12</version>
</dependency>

三,代碼段

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

import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.Border;
import jxl.format.BorderLineStyle;
import jxl.format.Colour;
import jxl.format.UnderlineStyle;
import jxl.format.VerticalAlignment;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;

/**
* @author 
* @createDate
* @Description:  
*/

public class FileTest {
	
	public static void main(String[] args) throws IOException, WriteException {
		String url = "D:\\addressTest.xlsx";
		//創建文件
		//File file = createFiles(url);
		File file = new File(url);
		//創建寫工作簿對象
		WritableWorkbook workbook = Workbook.createWorkbook(file);
		//工作表
		WritableSheet sheet = workbook.createSheet("測試地址列表", 0);
		//設置字體
		WritableFont font = new WritableFont(WritableFont.ARIAL,14,WritableFont.BOLD,false,UnderlineStyle.NO_UNDERLINE,Colour.BLACK);
		WritableCellFormat format = new WritableCellFormat(font);
		
		//設置背景顏色
		format.setBackground(Colour.WHITE);
		
		//設置邊框
		format.setBorder(Border.ALL, BorderLineStyle.DASH_DOT);
		
		//設置文字居中對齊方式
		format.setAlignment(Alignment.CENTRE);
		
		//設置垂直居中
		format.setVerticalAlignment(VerticalAlignment.CENTRE);
		
		//分別給1,5,6列設置不同的寬度
		sheet.setColumnView(0, 15);
		sheet.setColumnView(4, 65);
		sheet.setColumnView(5, 35);
		
		//給sheet電子版中所有的列設置默認的寬度
		sheet.getSettings().setDefaultColumnWidth(20);
		
		// 給sheet電子版中所有的行設置默認的高度,高度的單位是1/20個像素點,但設置這個貌似就不能        自動換行了
        // sheet.getSettings().setDefaultRowHeight(30 * 20);
		
		//設置自動換行
		format.setWrap(true);
		
		//單元格
		Label label0 = new Label(0,0,"ID",format);
		Label label1 = new Label(1,0,"省",format);
		Label label2 = new Label(2,0,"市",format);
		Label label3 = new Label(3,0,"區",format);
		
		sheet.addCell( label0 );
		sheet.addCell( label1 );
		sheet.addCell( label2 );
		sheet.addCell( label3 );
		
		//給第二行設置背景,字體顏色,對齊方式
		WritableFont font2 = new WritableFont(WritableFont.ARIAL,14,WritableFont.NO_BOLD,false,UnderlineStyle.NO_UNDERLINE,Colour.BLACK);
		WritableCellFormat format2 = new WritableCellFormat();
		
		//設置文字居中對齊方式
		format2.setAlignment(Alignment.CENTRE);
		
		//設置垂直居中
		format2.setVerticalAlignment(VerticalAlignment.CENTRE);
		format2.setBackground(Colour.WHITE);
		format2.setBorder(Border.ALL, BorderLineStyle.THIN);
		format2.setWrap(true);
		
		//記錄行數
		int  n = 1;
		
		//查詢所有的地址
		List<RegionTest> listRegion = new ArrayList<>();
		listRegion = RegoinTest();
		if(listRegion != null && listRegion.size() > 0){
			for(RegionTest regionTest : listRegion){
				Label lb0 = new Label(0,n,regionTest.getId()+"",format2);
				Label lb1 = new Label(1,n,regionTest.getProvince(),format2);
				Label lb2 = new Label(2,n,regionTest.getCity()+"",format2);
				Label lb3 = new Label(3,n,regionTest.getArea()+"",format2);
				
				sheet.addCell(lb0);
				sheet.addCell(lb1);
				sheet.addCell(lb2);
				sheet.addCell(lb3);
				n++;
			}
		}
		
		workbook.write();
		workbook.close();

		//開始讀文件
		InputStream inputStream = new FileInputStream(file);
		try {
			List<List<String>> list = getData(inputStream, 0);
			System.out.println("讀取文件的值爲:"+JacksonUtil.java2json(list));
		} catch (EncryptedDocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvalidFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
	}
	
	/**
	 * 創建文件(不寫東西)
	 * url文件路徑
	 * @throws IOException 
	 * */
	public static File createFiles(String url) throws IOException{
		File file = new File(url);
		file.createNewFile();
		return file;
	}
	
	/**
	 * 在excel裏面藥寫入的東西
	 * */
	
	public  static List<RegionTest> RegoinTest(){
		List<RegionTest> listRegoin = new ArrayList<RegionTest>();
		RegionTest region1 = new RegionTest(); 
		region1.setId(1);
		region1.setProvince("廣東省");
		region1.setCity("深圳市");
		region1.setArea("福田區");
		listRegoin.add(region1);
		
		RegionTest region2 = new RegionTest();
		region2.setId(2);
		region2.setProvince("廣西省");
		region2.setCity("南寧市");
		region2.setArea("直轄區");
		listRegoin.add(region2);
		
		RegionTest region3 = new RegionTest();
		region3.setId(3);
		region3.setProvince("江西省");
		region3.setCity("贛州市");
		region3.setArea("南康區");
		listRegoin.add(region3);
		
		
		RegionTest region4 = new RegionTest();
		region4.setId(4);
		region4.setProvince("江蘇省");
		region4.setCity("蘇州市");
		region4.setArea("姑蘇區");
		listRegoin.add(region4);
		
		RegionTest region5 = new RegionTest();
		region5.setId(5);
		region5.setProvince("上海市");
		region5.setCity("上海市");
		region5.setArea("嘉定區");	
		listRegoin.add(region5);
		
		RegionTest region6 = new RegionTest();
		region6.setId(6);
		region6.setProvince("上海市");
		region6.setCity("上海市");
		region6.setArea("青浦區");	
		listRegoin.add(region6);
		return listRegoin;
	}

/**
	 * 
	 * 讀取Excel的內容,第一維數組存儲的是一行中格列的值,二維數組存儲的是多少個行
	 * 
	 * @param file
	 *            讀取數據的源Excel
	 * 
	 * @param ignoreRows
	 *            讀取數據忽略的行數,比喻行頭不需要讀入 忽略的行數爲1
	 * 
	 * @return 讀出的Excel中數據的內容
	 * 
	 * @throws FileNotFoundException
	 * 
	 * @throws IOException
	 * @throws InvalidFormatException 
	 * @throws EncryptedDocumentException 
	 * 
	 */

	public static List<List<String>> getData(InputStream file, int ignoreRows)

			throws FileNotFoundException, IOException, EncryptedDocumentException, InvalidFormatException {

		List<List<String>> result = new ArrayList<>();

		org.apache.poi.ss.usermodel.Workbook workbook = WorkbookFactory.create(file);
	    Sheet sheet = workbook.getSheetAt(0);
	    
	    
	    DataFormatter formatter = new DataFormatter();
	    for (Row row : sheet) {
			Iterator<Cell> rowIt = row.iterator();
			
			String rowCell = "";
			List<String> rowsList = new ArrayList<>();
	    	while ( rowIt.hasNext() ) {
	    		Cell cell = rowIt.next();
	            CellReference cellRef = new CellReference(cell.getRow().getRowNum(), cell.getColumnIndex());
	            //單元格名稱
	            System.out.print(cellRef.formatAsString());
	            System.out.print(" - ");

	            //通過獲取單元格值並應用任何數據格式(Date,0.00,1.23e9,$ 1.23等),獲取單元格中顯示的文本
	            String text = formatter.formatCellValue(cell);
	            /*System.out.print(text);*/
	            CellType cellType = cell.getCellTypeEnum();
	            cellType.compareTo(CellType.STRING);
	             //獲取值並自己格式化
	            	// 字符串型
	            if( cellType.compareTo( CellType.STRING ) == 0 ){
	            	rowCell = cell.getRichStringCellValue().getString();
	            }else if ( cellType.compareTo( CellType.NUMERIC ) == 0 ){
	            	
	            	if (DateUtil.isCellDateFormatted(cell)) { // 如果是date類型則 ,獲取該cell的date值
	            		rowCell = cell.getDateCellValue() + "";
	            	} else {// 純數字
	            		rowCell = cell.getNumericCellValue() + "";
	            	}
	            }else if ( cellType.compareTo( CellType.BOOLEAN ) == 0 ){
	            	rowCell = cell.getBooleanCellValue() + "";
	            }
	            else if ( cellType.compareTo( CellType.FORMULA ) == 0 ){
	            	rowCell = cell.getCellFormula() + "";
	            }
	            else if ( cellType.compareTo( CellType.BLANK ) == 0 ){
	            }
	            else if ( cellType.compareTo( CellType.ERROR ) == 0 ){
	            }else{
	            }
	            System.out.print( rowCell + "  | ");
	            rowsList.add(rowCell);
	    	}
	    	System.out.println();
	    	result.add(rowsList);
	    }
		return result;
	}


}

JXL開發Excel文檔地址:https://www.cr173.com/html/10377_1.html 

參考地址:https://www.cnblogs.com/dyh2025/p/9311118.html

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