Apache POI - Java操作Excel

★、POI中很多组件并不是都能用上,根据需要选择自己需要的,我这里用到的就是SS(HSSF+XSSF)了,分别针对xls和xlsx,一般应该用HSSF就ok了,还是用office2003的人多一些

Apache POI - Java操作Excel

★、用的包大多数这个路径下的org.apache.poi.ss.usermodel

★、poi-examples-3.6-20091214.jar这个文件里面有例子,可以做个参照

Apache POI - Java操作Excel

★、如果处理的文件可能是xls也可能是xlsx的,怎么办?
方法1:处理前判断,然后分别用不同的方法去处理
方法2:使用接口操作,输出文件的时候,根据类型保存
    //save workbook
    String file = "picture.xls";
    if(wb instanceof XSSFWorkbook) file += "x";
    FileOutputStream fileOut = new FileOutputStream(file);
    wb.write(fileOut);
    fileOut.close();



★、参考网址:
http://poi.apache.org/
http://poi.apache.org/spreadsheet/quick-guide.html
http://developers.sun.com.cn/blog/functionalca/entry/java读写excel简介




★、写个demo,ExcelUtil.java
package core.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
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.junit.Test;

import core.dao.DaoImpl;

/**
 * Description: <br>
 * 2010-4-16
 * 
 * @author huxiao [email protected]
 */
public class ExcelUtil {

	private static final String filepath = "F:/job/workspace_huxiao_new/_testpoi/src/test/file/workbook.xls";

	/**
	 * description: 把一个List生成为Excel<br>
	 * 
	 * @param linkedList
	 * @param file
	 *            2010-4-16
	 * @author huxiao [email protected]
	 */
	public static void list2excel(List<Map<String, String>> list, List<String> keyList, File file) {
		List<LinkedHashMap<String, String>> linkedList = new ArrayList<LinkedHashMap<String, String>>();
		for (Map<String, String> map : list) {
			LinkedHashMap<String, String> tmpMap = new LinkedHashMap<String, String>();
			for (String key : keyList) {
				tmpMap.put(key, map.get(key));
			}
			linkedList.add(tmpMap);
		}

		if (!file.isDirectory()) {
			file.getParentFile().mkdirs();
		}
		Workbook wb = new HSSFWorkbook();
		Sheet sheet = wb.createSheet("Sheet1");

		for (int i = 0; i < linkedList.size(); i++) {
			Row row = sheet.createRow(i);
			Map<String, String> map = linkedList.get(i);
			int column = 1;
			for (String key : map.keySet()) {
				Cell cell = row.createCell(column++);
				cell.setCellValue(map.get(key));
			}
		}
		try {
			FileOutputStream fileOut = new FileOutputStream(file);
			wb.write(fileOut);
			fileOut.close();
		} catch (Exception e) {
			System.out.println("生成文件出错");
			e.printStackTrace();
		}
	}

	/**
	 * description: 读取一个Excel文件并返回List<br>
	 * 
	 * @param keyList
	 * @param file
	 * @return 2010-4-19
	 * @author huxiao [email protected]
	 */
	public static List<Map<String, String>> excel2List(List<String> keyList, File file) {
		if (!file.isFile()) {
			throw new RuntimeException(file + " 不存在");
		}
		POIFSFileSystem fs = null;
		HSSFWorkbook wb = null;
		HSSFSheet sheet = null;
		try {
			fs = new POIFSFileSystem(new FileInputStream(file));
			wb = new HSSFWorkbook(fs);
			sheet = wb.getSheetAt(0);
		} catch (IOException e) {
			System.out.println(file + "读取错误");
			e.printStackTrace();
		}
		List<Map<String, String>> resultList = new ArrayList<Map<String, String>>();
		for (Row row : sheet) {
			Map<String, String> tmpMap = new HashMap<String, String>();
			for (Cell cell : row) {
				int columnIndex = cell.getColumnIndex();
				tmpMap.put(keyList.get(columnIndex - 1), cell.getStringCellValue());
			}
			resultList.add(tmpMap);
		}
		return resultList;
	}

	

	/**
	 * description: 测试生成Excel<br>
	 * 2010-4-19
	 * 
	 * @author huxiao [email protected]
	 */
	@Test
	public void testList2Excel() {
		List<Map<String, String>> list = new DaoImpl().queryForList("select * from user");

		// 因为hashmap是无序的,所以在这里自定义key的顺序,根据这个keyList把hashMap转成LinkedHashMap再循环
		// 当需求固定之后,可以直接写到配置文件里面,就不用手写了
		List<String> keyList = new ArrayList<String>();
		keyList.add("ID");
		keyList.add("USERNAME");
		keyList.add("PASSWORD");

		list2excel(list, keyList, new File(filepath));
	}

	/**
	 * description: 测试excel2list<br>
	 * 
	 * @param args
	 *            2010-4-19
	 * @author huxiao [email protected]
	 */
	@Test
	public void testExcel2List() {
		// 取出来的时候就不必按顺序啦,但是你要制定key是什么啊,否则怎么存储到map里面呢?
		// 不用担心,实际操作的时候这个东西可以从数据库或者配置文件中获取,不用每次手写的
		List<String> keyList = new ArrayList<String>();
		keyList.add("ID");
		keyList.add("USERNAME");
		keyList.add("PASSWORD");

		List<Map<String, String>> list = excel2List(keyList, new File(filepath));
		System.out.println(list);
	}

}

你可能感兴趣的:(java,apache,qq,Excel,JUnit)