• [Training Video


    package com.file.properties;
    
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Date;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    import java.util.Set;
    
    import org.apache.poi.hssf.usermodel.HSSFSheet;
    import org.apache.poi.hssf.usermodel.HSSFWorkbook;
    import org.apache.poi.ss.usermodel.Cell;
    import org.apache.poi.ss.usermodel.RichTextString;
    import org.apache.poi.ss.usermodel.Row;
    
    public class CreateNewExcel {
    		static void createExcelFile(File createFile,String sheetName, Map<String, Object[]> data) {	
    		
    		HSSFWorkbook workbook = new HSSFWorkbook();
    		HSSFSheet sheet = workbook.createSheet(sheetName);
    		
    		Set<String> keySet=data.keySet();
    		List<String> keyList=new ArrayList<String>(keySet);
    		Collections.sort(keyList);
    			
    		int rownum = 0;
    		for (String key : keyList) {
    			Row row = sheet.createRow(rownum++);
    			Object[] objArr = (Object[]) data.get(key);
    			int cellnum = 0;
    			for (Object obj : objArr) {
    				Cell cell = row.createCell(cellnum++);
    				if(obj instanceof Date) 
    					cell.setCellValue((RichTextString)obj);
    				else if(obj instanceof Boolean)
    					cell.setCellValue((Boolean)obj);
    				else if(obj instanceof String)
    					cell.setCellValue((String)obj);
    				else if(obj instanceof Double)
    					cell.setCellValue((Double)obj);
    			}
    		}
    		
    		try {
    			FileOutputStream out = new FileOutputStream(createFile);
    			workbook.write(out);
    			out.close();
    			System.out.println("Excel written successfully..");
    			
    		} catch (FileNotFoundException e) {
    			e.printStackTrace();
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
    	}
    
    	/**
    	 * @param args
    	 */
    	public static void main(String[] args) {
    		File createFile = new File("D:\SoapUIStudy\createExcelFile.xls");
    		String sheetName = "Sample sheet";
    		Map<String, Object[]> data = new HashMap<String, Object[]>();
    		data.put("1", new Object[] {"Emp No.", "Name", "Salary"});
    		data.put("2", new Object[] {1d, "John", 1500000d});
    		data.put("3", new Object[] {2d, "Sam", 800000d});
    		data.put("4", new Object[] {3d, "Dean", 700000d});
    		createExcelFile(createFile,sheetName,data);
    	}
    
    }
    

     Result :

  • 相关阅读:
    内联函数与宏定义
    三色塔汉诺塔 三色
    Volatile C
    阶乘 简单递归实现
    双色汉诺塔 算法 (递归)
    向上向下排序
    Convert、Parse、TryParse、(int)等区别
    ToString()、Convert.ToString()、(string)、as string 的区别[转]
    ASP.NET页面刷新方法大集合
    getElementByID,getElementsByName,getElementsByTagName的区别
  • 原文地址:https://www.cnblogs.com/MasterMonkInTemple/p/4582595.html
Copyright © 2020-2023  润新知