想不想像寫jsp一樣的去定義一個excel模板,然後再像用jstl和el運算式那樣往excel模板裡面傳入變數,現在用jxls全部可以輕鬆搞定了,核心代碼非常簡單。 [java] //調用引擎產生excel報表 XLSTransformer transformer = new XLSTransformer(); Workbook workbook = transformer.transformMultipleSheetsList(is, objects, listSheetNames, "list", new HashMap(), 0); www.2cto.comworkbook.write(new FileOutputStream("c:\\xlsExportUtils.xls")); 下面來看看excel模板是怎麼定義的。 是不是和jsp裡面的jstl很像。 下面是這個測試例子的完整代碼: [java] import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import net.sf.jxls.exception.ParsePropertyException; import net.sf.jxls.transformer.XLSTransformer; import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import org.apache.poi.ss.usermodel.Workbook; /** * @author 魯炬 * */ public class XlsExportUtil { public static void createExcel() throws ParsePropertyException, InvalidFormatException, IOException {} @SuppressWarnings("rawtypes") public static void main(String[] args) throws ParsePropertyException, InvalidFormatException, IOException { //擷取Excel模板檔案 String fileDir = XlsExportUtil.class.getResource("").getFile(); String filePath = fileDir + "XlsExportUtilTemplate.xls"; System.out.println("excel template file:" + filePath); FileInputStream is = new FileInputStream(filePath); //建立測試資料 Map<String, Object> map = new HashMap<String, Object>(); List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(); Map<String, Object> map1 = new HashMap<String, Object>(); map1.put("name", "電視"); map1.put("price", "3000"); map1.put("desc", "3D電視機"); map1.put("備忘", "中文測試"); Map<String, Object> map2 = new HashMap<String, Object>(); map2.put("name", "空調"); map2.put("price", "2000"); map2.put("desc", "變頻空調"); map1.put("備忘", "測試中文"); list.add(map1); list.add(map2); map.put("list", list); ArrayList<List> objects = new ArrayList<List>(); objects.add(list); objects.add(list); objects.add(list); objects.add(list); //sheet的名稱 List<String> listSheetNames = new ArrayList<String>(); listSheetNames.add("1"); listSheetNames.add("2"); listSheetNames.add("3"); listSheetNames.add("4"); //調用引擎產生excel報表 XLSTransformer transformer = new XLSTransformer(); Workbook workbook = transformer.transformMultipleSheetsList(is, objects, listSheetNames, "list", new HashMap(), 0); workbook.write(new FileOutputStream("c:\\xlsExportUtils.xls")); } }