1. 程式人生 > >Java根據模板建立excel檔案

Java根據模板建立excel檔案

1.首先匯入xml檔案,src下建包xml,將student.xml檔案放入此資料夾中


<excel id="student" code="student" name="學生資訊匯入">
    <colgroup>
        <col index="A" width='17em'></col>
        <col index="B" width='17em'></col>
        <col index="C" width='17em'></col>
        <col index="D" width='17em'></col>
        <col index="E" width='17em'></col>
        <col index="F" width='17em'></col>        
    </colgroup>
    <title>
        <tr height="16px">
            <td rowspan="1" colspan="6" value="學生資訊匯入" />
        </tr>
    </title>
    <thead>
        <tr height="16px">
        	<th value="編號" />
            <th value="姓名" />
            <th value="年齡" />
            <th value="性別" />
            <th value="出生日期" />
            <th value=" 愛好" />            
        </tr>
    </thead>
    <tbody>
        <tr height="16px" firstrow="2" firstcol="0" repeat="5">
            <td type="string" isnullable="false" maxlength="30" /><!--使用者編號 -->
            <td type="string" isnullable="false" maxlength="50" /><!--姓名 -->
            <td type="numeric" format="##0" isnullable="false" /><!--年齡 -->
            <td type="enum" format="男,女" isnullable="true" /><!--性別 -->
            <td type="date" isnullable="false" maxlength="30" /><!--出生日期 -->
            <td type="enum" format="足球,籃球,乒乓球" isnullable="true" /><!--愛好 -->
        </tr>
    </tbody>


2.匯入架包

1)commons-lang3-3.1.jar

2)jdom.jar

3)commons-io-2.2.jar

4)poi-3.11-20141221.jar

3.建立測試類

1)sax解析xml檔案

//獲取解析xml檔案路徑
		String path = System.getProperty("user.dir") + "/xml/student.xml";
		File file = new File(path);
		SAXBuilder builder = new SAXBuilder();
		//解析xml檔案
		Document parse = builder.build(file);

2)建立excel

//建立Excel
		HSSFWorkbook wb = new HSSFWorkbook();
		//建立sheet
		HSSFSheet sheet = wb.createSheet("Sheet0");

3)從xml檔案中取值

//獲取xml檔案跟節點
		Element root = parse.getRootElement();
		//獲取模板名稱
		String templateName = root.getAttribute("name").getValue();

4)設定excel列寬

int rownum = 0;
		int column = 0;
		//設定列寬
		Element colgroup = root.getChild("colgroup");
		setColumnWidth(sheet,colgroup);
		此處設定列寬,將其封裝成一個方法
	private static void setColumnWidth(HSSFSheet sheet, Element colgroup) {
		List<Element> cols = colgroup.getChildren("col");
		for (int i = 0; i < cols.size(); i++) {
			Element col = cols.get(i);
			//獲取col的設定
			Attribute width = col.getAttribute("width");
			//正則表示式擷取字串,獲取xml中列的單位
			String unit = width.getValue().replaceAll("[0-9,\\.]", "");
			//獲取寬度值
			String value = width.getValue().replaceAll(unit, "");
			int v=0;
			//poi寬度轉化為excel寬度
			if(StringUtils.isBlank(unit) || "px".endsWith(unit)){
				//空或者px單位的寬度轉換為excel寬度
				v = Math.round(Float.parseFloat(value) * 37F);
				//em單位的寬度轉換為excel寬度
			}else if ("em".endsWith(unit)){
				v = Math.round(Float.parseFloat(value) * 267.5F);
			}
			sheet.setColumnWidth(i, v);
		}
	}

5)設定標題
Element title = root.getChild("title");
			List<Element> trs = title.getChildren("tr");
			for (int i = 0; i < trs.size(); i++) {
				Element tr = trs.get(i);
				List<Element> tds = tr.getChildren("td");
				HSSFRow row = sheet.createRow(rownum);
				for(column = 0;column <tds.size();column ++){
					Element td = tds.get(column);
					//建立單元格
					HSSFCell cell = row.createCell(column);
					Attribute rowSpan = td.getAttribute("rowspan");
					Attribute colSpan = td.getAttribute("colspan");
					Attribute value = td.getAttribute("value");
					if(value !=null){
						String val = value.getValue();
						cell.setCellValue(val);
						int rspan = rowSpan.getIntValue() - 1;
						int cspan = colSpan.getIntValue() -1;
						//合併單元格居中	(開始行,結束行,開始列,結束列)						
						sheet.addMergedRegion(new CellRangeAddress(rspan, rspan, 0, cspan));
					}
				}
				rownum ++;
			}

6)設定單元格樣式

HSSFCellStyle cellStyle = wb.createCellStyle();
				//居中
				cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
				//設定字型
						HSSFFont font = wb.createFont();
						font.setFontName("仿宋_GB2312");
						font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);//字型加粗
//						font.setFontHeight((short)12);//設定高度
						font.setFontHeightInPoints((short)12);
						//將字型加入樣式中
						cellStyle.setFont(font);
						//設定單元格樣式
						cell.setCellStyle(cellStyle);


7)設定表頭

Element thead = root.getChild("thead");
			trs = thead.getChildren("tr");
			//迴圈得到節點資訊
			for (int i = 0; i < trs.size(); i++) {
				Element tr = trs.get(i);
				//建立excel行
				HSSFRow row = sheet.createRow(rownum);
				//獲取節點資訊
				List<Element> ths = tr.getChildren("th");
				//迴圈列
				for(column = 0;column < ths.size();column++){
					//元素
					Element th = ths.get(column);
					//屬性值
					Attribute valueAttr = th.getAttribute("value");
					HSSFCell cell = row.createCell(column);
					if(valueAttr != null){
						String value =valueAttr.getValue();
						//單元格賦值
						cell.setCellValue(value);
					}
				}
				rownum++;
			}


8)設定區域樣式

//設定資料區域樣式
			Element tbody = root.getChild("tbody");
			Element tr = tbody.getChild("tr");
			//repeat:初始化行數
			int repeat = tr.getAttribute("repeat").getIntValue();
			
			List<Element> tds = tr.getChildren("td");
			for (int i = 0; i < repeat; i++) {
				HSSFRow row = sheet.createRow(rownum);
				for(column =0 ;column < tds.size();column++){
					Element td = tds.get(column);
					HSSFCell cell = row.createCell(column);
					setType(wb,cell,td);
				}
				rownum++;
			}


			設定屬性及樣式封裝的方法
	private static void setType(HSSFWorkbook wb, HSSFCell cell, Element td) {
		Attribute typeAttr = td.getAttribute("type");
		String type = typeAttr.getValue();
		HSSFDataFormat format = wb.createDataFormat();
		HSSFCellStyle cellStyle = wb.createCellStyle();
		//判斷節點型別
		//數字型別
		if("NUMERIC".equalsIgnoreCase(type)){
			cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
			Attribute formatAttr = td.getAttribute("format");
			String formatValue = formatAttr.getValue();
			//如果不為空賦值,為空賦初始值
			formatValue = StringUtils.isNotBlank(formatValue)? formatValue : "#,##0.00";
			cellStyle.setDataFormat(format.getFormat(formatValue));
		//字串型別
		}else if("STRING".equalsIgnoreCase(type)){
			cell.setCellValue("");
			cell.setCellType(HSSFCell.CELL_TYPE_STRING);
			//格式化 @表示文字
			cellStyle.setDataFormat(format.getFormat("@"));
		//日期型別
		}else if("DATE".equalsIgnoreCase(type)){
			cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
			cellStyle.setDataFormat(format.getFormat("yyyy-m-d"));
		//列舉型別
		}else if("ENUM".equalsIgnoreCase(type)){
			CellRangeAddressList regions = 
			//方法引數(開始行,結束行,開始列,結束列)
				new CellRangeAddressList(cell.getRowIndex(), cell.getRowIndex(), 
						cell.getColumnIndex(), cell.getColumnIndex());
			Attribute enumAttr = td.getAttribute("format");
			String enumValue = enumAttr.getValue();
			//載入下拉列表內容
			DVConstraint constraint = 
			//方法引數(下拉列表陣列)
				DVConstraint.createExplicitListConstraint(enumValue.split(","));
			//資料有效性物件
			HSSFDataValidation dataValidation = new HSSFDataValidation(regions, constraint);
			wb.getSheetAt(0).addValidationData(dataValidation);
		}
		cell.setCellStyle(cellStyle);
	}


9)將檔案儲存到本地

File tempFile = new File("e:/" + templateName + ".xls");
			tempFile.delete();
			tempFile.createNewFile();
			FileOutputStream stream = FileUtils.openOutputStream(tempFile);
			wb.write(stream);
			stream.close();


4.在E盤將找到生成的excel檔案,其中年齡初始值為0(xml中賦初始值為0),出生年月1900-1-0(架包預設),性別和愛好為下拉列表

相關推薦

Java根據模板建立excel檔案

1.首先匯入xml檔案,src下建包xml,將student.xml檔案放入此資料夾中 <excel id="student" code="student" name="學生資訊匯入"> <colgroup> <co

java根據模板匯出excel(二)

       最近在做一個專案,關於excel的匯出問題,上網查了很多,最後自己整理並編寫了關於模板匯出的方法,可能會有一些侷限性,但是對於簡單的模板匯出功能是可以實現的,先留下筆記,以供日後參考!思路其實很簡單,主要分為:(1)讀取模板excel(2)迴圈模

Java根據模板匯出Excel並生成多個Sheet

因為最近用報表匯出比較多,所有就提成了一個工具類,本工具類使用的場景為  根據提供的模板來匯出Excel報表 並且可根據提供的模板Sheet頁進行復制 從而實現多個Sheet頁的需求, 使用本工具類時,如果需求是每個Sheet頁中的資料都不一致,但是表格樣式和模板都一樣 那

Java根據模板生成excel並下載

需要用到的jar包有freemarker-2.3.18.jar,freemarker-util-0.0.1-SNAPSHOT.jar,jxl-2.6.10.jar,jxl-report-1.0.jar,這些網上都有,可以去找 來吧,直接上乾貨。excel模板如圖: 很容

java根據模板生成pdf檔案並匯出(轉)

import java.io.ByteArrayOutputStream; import java.io.FileOutputStream; import java.io.IOException; import com.itextpdf.text.Document; import com.itextpdf.

Java建立Excel檔案Java Excel API的使用

Java Excel API的使用  Java Excel API(JXL)是一個成熟開源的Java類庫,用來操作Excel電子表格,支援讀取,修改,寫入等操作。這個專案基於GPL釋出,與poi比較,對中文有很好的支援。而且支援PNG格式圖片以及各種數字型別。當然poi除了可

【Apache POI】Java Web根據模板匯出word檔案

最近工作中遇到一個需求:根據word模板文件匯出word檔案。 查閱了一些資料,發現Apache POI可以實現文件讀寫的功能,於是就研究了一下,總結如下: POI詳細介紹: Apache POI是一個開源的Java讀寫Excel、WORD等微軟OLE2元件

java利用poi讀取Excel檔案

java讀取Excel檔案,筆者認為:從結構上來看,Excel檔案是由一個一個的單元格組成的,有點像細胞cell,逐行的排列。那麼我們讀的時候也應該逐行逐行的讀,從左到右的尋找每一個cell。一、例項程式碼: 只是實現了一種方式,因為依照讀取內容的不同,讀取的後想要的操作不同,因此不能苟同全部,只是方法是相

根據模板生成HTML檔案

場景描述: 最近寫一個部落格系由於需要批量生成網頁,所以寫這麼一個小功能 直接上程式碼了 html模板(根據需要自己隨便寫,這這是個測試) <!DOCTYPE html> <html> <head> <meta charse

Java 利用 poi 生成 Excel檔案的通用例子

在用java 寫資料庫應用的時候, 通常會生成各種報表,而這些報表可能會被匯出為各種格式的檔案,比如Excel文件,pdf 文件等等. 今天先做了一個生成Excel 文件的例子,主要解決以下問題: 生成 Excel 文件. 保護生成Excel文件,設定密碼訪問. 自動對生成的Exce

Java生成和操作Excel檔案

JAVA EXCEL API:是一開放原始碼專案,通過它Java開發人員可以讀取Excel檔案的內容、建立新的Excel檔案、更新已經存在的Excel檔案。使用該API非Windows作業系統也可以通過純Java應用來處理Excel資料表。因為它是使用Java編寫的,所以我們在Web應用中可以通過

Java將資料以Excel檔案形式匯出後臺程式碼實現

下面程式碼實現所需jar包:   tomcat-embed-core-8.5.11.jar;   commons-lang3-3.0.1.jar;   commons-io-2.5.jar;   poi-3.9.jar   (下載地址:https://files.cnblogs.com/files/

使用EasyPoi根據模板匯出Excel或word文件

接著上篇文章 Java根據模板匯出Excel並生成多個Sheet 簡單介紹下EasyPoi的使用,直接上程式碼吧 首先當然是先引入jar包了,看下圖 其次,還是貼程式碼吧看例項,下面是根據模板匯出的工具類,包含Excel和word /**  * 匯

python建立Excel檔案資料的方法

# -*- coding: utf-8 -*-# @Time : 2018/12/6 17:10# @Author : suchao# @Disc: : 生成10000條Excel資料# @File : 1000data.py# @Software: PyCharmimport xlrd ,

java根據模板匯出pdf(動態增加模板頁數)

這兩天碰到了一個根據模板匯出pdf的需求,研究了幾天以後,發現網上的資料不太齊全,主要是沒找到既根據模板匯出,又可以動態增加頁數的例子。只能通過各種資料結合來實現這個需求了(其實是懶得看iText英文文件,這個以後得改過來)。 下面先來說下pdf匯出主要的兩種方

JAVA POI上傳excel檔案到資料庫並備份(上)

一、電商系統和辦公系統時常會用到Excel的匯入與匯出,在JAVA程式碼實現時,通常使用POI來處理,今天用一個demo為大家介紹POI上傳excel檔案並將資料匯入資料庫的實現過程。demo是一個jsp/servlet+maven的web專案。 二、環境:     資料庫

Java POI 讀寫Excel 檔案簡單實現

整理FileUtils的一些方法,只是一些初步實現,剛寫完就掛上來了… 友情提示:**過於結構化,沒太多潤色....碼的不好還請諸位海涵並多提意見** 關聯的型別 資源 型別 說明 Workbook 介面 Ex

java工具類之Excel檔案匯入、讀取資料(支援xls、和xlsx)

所需的jar包:poi的jar包儘量保持一致,不然會報版本不一致的錯誤下面是程式碼:package ReadExcel; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.

java 利用 poi 生成 Excel檔案與spring使用檔案流形式下載檔案

本文為結合參考資料整合而來。 第一步導包: 三個jar: poi poi-ooxml poi-ooxml-schemas maven: <properties> <poi.version>3.12</p

java使用POI讀取excel檔案,相容xls和xlsx

public List<Double> readExcels(InputStream is)throws Exception{List<Double> xlsxList = new ArrayList<Double>();    try {             if(i