ITeye博客

Java操作Excel文件导入

snowolf · 2012-06-27 17:33 · Java/Basic · 开源软件 · Markdown

用Excel作为数据源,通过Java Web进行导入,需要POI的jar。 apachepoi(org.apache.poi 3.8) :) 可以支持公式、日期等格式! :D 不说废话,上代码:


/**
 * Jun 25, 2012
 */

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

import org.apache.commons.io.FilenameUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellValue;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

/**
 * Excel组件
 * 
 * @author Snowolf
 * @version 1.0
 * @since 1.0
 */
public abstract class ExcelHelper {

	/**
	 * Excel 2003
	 */
	private final static String XLS = "xls";
	/**
	 * Excel 2007
	 */
	private final static String XLSX = "xlsx";
	/**
	 * 分隔符
	 */
	private final static String SEPARATOR = "|";

	/**
	 * 由Excel文件的Sheet导出至List
	 * 
	 * @param file
	 * @param sheetNum
	 * @return
	 */
	public static List<String> exportListFromExcel(File file, int sheetNum)
			throws IOException {
		return exportListFromExcel(new FileInputStream(file),
				FilenameUtils.getExtension(file.getName()), sheetNum);
	}

	/**
	 * 由Excel流的Sheet导出至List
	 * 
	 * @param is
	 * @param extensionName
	 * @param sheetNum
	 * @return
	 * @throws IOException
	 */
	public static List<String> exportListFromExcel(InputStream is,
			String extensionName, int sheetNum) throws IOException {

		Workbook workbook = null;

		if (extensionName.toLowerCase().equals(XLS)) {
			workbook = new HSSFWorkbook(is);
		} else if (extensionName.toLowerCase().equals(XLSX)) {
			workbook = new XSSFWorkbook(is);
		}

		return exportListFromExcel(workbook, sheetNum);
	}

	/**
	 * 由指定的Sheet导出至List
	 * 
	 * @param workbook
	 * @param sheetNum
	 * @return
	 * @throws IOException
	 */
	private static List<String> exportListFromExcel(Workbook workbook,
			int sheetNum) {

		Sheet sheet = workbook.getSheetAt(sheetNum);

		// 解析公式结果
		FormulaEvaluator evaluator = workbook.getCreationHelper()
				.createFormulaEvaluator();

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

		int minRowIx = sheet.getFirstRowNum();
		int maxRowIx = sheet.getLastRowNum();
		for (int rowIx = minRowIx; rowIx <= maxRowIx; rowIx++) {
			Row row = sheet.getRow(rowIx);
			StringBuilder sb = new StringBuilder();

			short minColIx = row.getFirstCellNum();
			short maxColIx = row.getLastCellNum();
			for (short colIx = minColIx; colIx <= maxColIx; colIx++) {
				Cell cell = row.getCell(new Integer(colIx));
				CellValue cellValue = evaluator.evaluate(cell);
				if (cellValue == null) {
					continue;
				}
				// 经过公式解析,最后只存在Boolean、Numeric和String三种数据类型,此外就是Error了
				// 其余数据类型,根据官方文档,完全可以忽略http://poi.apache.org/spreadsheet/eval.html
				switch (cellValue.getCellType()) {
				case Cell.CELL_TYPE_BOOLEAN:
					sb.append(SEPARATOR + cellValue.getBooleanValue());
					break;
				case Cell.CELL_TYPE_NUMERIC:
					// 这里的日期类型会被转换为数字类型,需要判别后区分处理
					if (DateUtil.isCellDateFormatted(cell)) {
						sb.append(SEPARATOR + cell.getDateCellValue());
					} else {
						sb.append(SEPARATOR + cellValue.getNumberValue());
					}
					break;
				case Cell.CELL_TYPE_STRING:
					sb.append(SEPARATOR + cellValue.getStringValue());
					break;
				case Cell.CELL_TYPE_FORMULA:
					break;
				case Cell.CELL_TYPE_BLANK:
					break;
				case Cell.CELL_TYPE_ERROR:
					break;
				default:
					break;
				}
			}
			list.add(sb.toString());
		}
		return list;
	}
}

由于Excel中的数据有日期、公式等等格式,参考http://poi.apache.org/spreadsheet/eval.html做了修改,完全兼容。 :D

当前的Excel,C列是根据A、B相乘计算而来,D列是日期格式:

测试下:


/**
 * Jun 25, 2012
 */

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

import static org.junit.Assert.*;
import org.junit.Test;

/**
 * 
 * @author Snowolf
 * @version 1.0
 * @since 1.0
 */
public class ExcelHelperTest {

	@Test
	public void test() {
		String path = "excel.xlsx";
		List<String> list = null;
		try {
			list = ExcelHelper.exportListFromExcel(new File(path), 0);
			assertNotNull(list);
		} catch (IOException e) {
			fail();
		}

	}
}

就是这样了

详见附件! :D

存档于此,备查~~ :D

评论(11)

  1. #11 楼 · zi_wu_xian · 2016-09-02 14:40

    好复杂啊,还是用PageOffice导入excel文件吧,代码简单,生成的文件格式规范

  2. #10 楼 · sandyagor · 2016-08-21 21:49

    这是一个maven工程,

  3. #9 楼 · Agwawaw · 2015-09-14 12:47

    项目总是报错,不知为什么

  4. #8 楼 · yu335738607 · 2015-08-24 11:22

    加qq335738607 沟通此问题

  5. #7 楼 · yu335738607 · 2015-08-24 11:22

    有excel 大小限制吗

  6. #6 楼 · zhenglu119 · 2013-06-05 14:55

    XSSFWorkbook 在3.8jar包的情况下。导入不进来, 是神马情况啊。

  7. #5 楼 · snowolf · 2012-06-29 06:36

    snowolf writes:

    [quote=snowolf][quote=programdolt]很好,getRichStringCellValue 日期,公式等都支持了?[/quote]通过 [code=java]FormulaEvaluator evaluator = workbook.getCreationHelper()
    .createFormulaEvaluator(); Cell cell = row.getCell(new Integer(j));
    CellValue cellValue = evaluator.evaluate(cell); [/code]进行公式、日期等等的解析,完全支持了![/quote] 当然,日期支持转换为数字了,需要重新转码了!

     case Cell.CELL_TYPE_NUMERIC:  
                        // 这里的日期类型会被转换为数字类型,需要判别后区分处理  
                        if (DateUtil.isCellDateFormatted(cell)) {  
                            sb.append(SEPARATOR + cell.getDateCellValue());  
                        } else {  
                            sb.append(SEPARATOR + cellValue.getNumberValue());  
                        }  
    
    

    这样就有对应的日期了,当然,你可以根据需要转换格式! :D

  8. #4 楼 · Function · 2012-06-28 13:42

    试试 jxl

  9. #3 楼 · snowolf · 2012-06-28 10:25

    snowolf writes:

    [quote=programdolt]很好,getRichStringCellValue 日期,公式等都支持了?[/quote]通过 [code=java]FormulaEvaluator evaluator = workbook.getCreationHelper()
    .createFormulaEvaluator(); Cell cell = row.getCell(new Integer(j));
    CellValue cellValue = evaluator.evaluate(cell); [/code]进行公式、日期等等的解析,完全支持了!

    当然,日期支持转换为数字了,需要重新转码了!

  10. #2 楼 · snowolf · 2012-06-28 09:26

    programdolt writes:

    很好,getRichStringCellValue 日期,公式等都支持了? 通过

    FormulaEvaluator evaluator = workbook.getCreationHelper()  
                    .createFormulaEvaluator(); 
    Cell cell = row.getCell(new Integer(j));  
                    CellValue cellValue = evaluator.evaluate(cell);  
    

    进行公式、日期等等的解析,完全支持了!

  11. #1 楼 · programdolt · 2012-06-27 18:05

    很好,getRichStringCellValue 日期,公式等都支持了?

评论功能维护中,当前仅展示历史评论。