`

poi读写excel文件(支持读取office 2003版本以下,或2007版本以上)

阅读更多
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.HashMap;

import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.DataFormat;
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;

public class ExcelReportFile {

	private static final long serialVersionUID = 612381396391426330L;

	private Workbook workBook = null;
	private HashMap<Integer, CellStyle> numberCellStyles = null;
	private CellStyle textCellStyle = null;
	private static int DEFAULT_SHEET_INDEX = 0;


	public ExcelReportFile(File file) throws FileNotFoundException, IOException {

        try {
        	//读取office 2007版本以上
        	workBook = new XSSFWorkbook(new FileInputStream(file));
        } catch (Exception ex) {
        	//读取office 2003版本以下
        	workBook = new HSSFWorkbook(new FileInputStream(file));
        } 

	}

	public Object getValue(int rowIndex, int colIndex) {
		return readCellValue(rowIndex, colIndex);
	}

	/**
	 * 通过行号,列号读取excel单元格数据
	 * 
	 * @param rowNo
	 * @param colNo
	 * @return
	 */
	public String getValueByNo(int rowNo, int colNo) {
		Object rtnValue = readCellValue(rowNo - 1, colNo - 1);
		String sValue = String.valueOf((rtnValue == null) ? "" : rtnValue);
		return sValue;
	}

	private Object readCellValue(int rowIndex, int colIndex) {

		Object sCellValue = null;
		Row row = workBook.getSheetAt(0).getRow(rowIndex);

		if (row != null) {
			Cell cell = row.getCell(colIndex);

			if (cell != null) {

				int cellType = cell.getCellType();

				// HSSFCell.CELL_TYPE_FORMULA

				// Empty
				if (cellType == Cell.CELL_TYPE_BLANK) {
					sCellValue = null;
					// int dCellValue = 0;
					// sCellValue = dCellValue;
				}

				// String
				if (cellType == Cell.CELL_TYPE_STRING) {
					sCellValue = cell.getRichStringCellValue().getString()
							.trim();
				}

				// Number
				if (cellType == Cell.CELL_TYPE_NUMERIC) {
					int dCellValue = (int) cell.getNumericCellValue();
					sCellValue = dCellValue;
				}

				// formula
				if (cellType == Cell.CELL_TYPE_FORMULA) {
					sCellValue = cell.getCellFormula();
				}

			}
		}

		return sCellValue;
	}

	public void writeNumber(int sheetIndex, int rowIndex, int colIndex,
			Number value, int scale) {

		Cell cell = getCell(sheetIndex, rowIndex, colIndex);
		// HSSFCellStyle cellStyle = getNumberCellStyle(scale);

		// cell.setCellStyle(cellStyle);
		cell.setCellValue(value.doubleValue());
	}

	public void writeText(int sheetIndex, int rowIndex, int colIndex,
			String value) {

		Cell cell = getCell(sheetIndex, rowIndex, colIndex);
		// HSSFCellStyle cellStyle = getTextCellStyle();
		// cell.setCellType(HSSFCell.CELL_TYPE_STRING);
		// cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("text"));
		// cell.setCellStyle(cellStyle);

		cell.setCellValue(new HSSFRichTextString(value));
	}

	public void writeText(int rowIndex, int colIndex, String value) {
		writeText(DEFAULT_SHEET_INDEX, rowIndex, colIndex, value);
	}

	public void writeTextByNo(int rowIndex, int colIndex, String value) {
		writeText(DEFAULT_SHEET_INDEX, rowIndex - 1, colIndex - 1, value);
	}

	public void writeNumber(int rowIndex, int colIndex, Number value, int scale) {
		writeNumber(DEFAULT_SHEET_INDEX, rowIndex, colIndex, value, scale);
	}

	public void writeNumberByNo(int rowIndex, int colIndex, Number value,
			int scale) {
		writeNumber(DEFAULT_SHEET_INDEX, rowIndex - 1, colIndex - 1, value,
				scale);
	}

	private Cell getCell(int sheetIndex, int rowIndex, int colIndex) {

		// Sheet
		Sheet sheet = null;
		try {
			sheet = workBook.getSheetAt(sheetIndex);
		} catch (IllegalArgumentException ex) {
			sheet = workBook.createSheet();
		}

		// Row
		Row row = null;
		row = sheet.getRow(rowIndex);
		if (row == null) {
			row = sheet.createRow(rowIndex);
		}

		// Cell
		Cell cell = null;
		cell = row.getCell(colIndex);
		if (cell == null) {
			cell = row.createCell(colIndex);
		}

		return cell;
	}

	private CellStyle getNumberCellStyle(int scale) {

		if (this.numberCellStyles == null) {
			this.numberCellStyles = new HashMap<Integer, CellStyle>();
		}

		if (this.numberCellStyles.get(Integer.valueOf(scale)) == null) {
			CellStyle numberCellStyle = workBook.createCellStyle();

			StringBuilder zeroBd = new StringBuilder();
			DataFormat format = this.workBook.createDataFormat();
			zeroBd.append("0");

			if (scale > 0) {
				zeroBd.append(".");
				for (int zCount = 0; zCount < scale; zCount++) {
					zeroBd.append("0");
				}
			}

			short doubleFormat = format.getFormat(zeroBd.toString());
			numberCellStyle.setDataFormat(doubleFormat);

			this.numberCellStyles.put(Integer.valueOf(scale), numberCellStyle);
			return numberCellStyle;
		} else {
			return this.numberCellStyles.get(Integer.valueOf(scale));
		}
	}

	public void write(OutputStream stream) throws IOException {
		if (this.workBook != null && stream != null) {
			this.workBook.write(stream);
		}
	}

	private CellStyle getTextCellStyle() {
		if (textCellStyle != null) {
			return textCellStyle;
		} else {
			return this.workBook.createCellStyle();
		}
	}

	/**
	 * 通过英文字母获得列号
	 * 
	 * @param colIndexStr
	 * @return
	 */
	public static int convertColIndexString2Number(String colIndexStr) {
		int len = colIndexStr.toUpperCase().length();
		char[] chars = colIndexStr.toCharArray();
		int col = 0;
		for (int index = 0; index < len; index++) {
			char ca = chars[index];
			int charAInt = Character.getNumericValue('A');
			int charInt = Character.getNumericValue(ca);

			BigDecimal bg = new BigDecimal(26);
			col = col + bg.pow(len - index - 1).intValue()
					* (charInt - charAInt + 1);
		}
		return col;
	}
	
}


所需jar包:
poi-3.8-20120326.jar
poi-ooxml-3.8-20120326.jar
poi-ooxml-schemas-3.8-20120326.jar
xbean.jar
缺一不可哦。
分享到:
评论

相关推荐

    使用POI读写Excel文件(兼容xls与xlsx版本)

    这篇博客“使用POI读写Excel文件(兼容xls与xlsx版本)”深入探讨了如何利用Apache POI库在Java环境中处理Excel文档。 首先,让我们了解一下Apache POI的基本概念。Apache POI提供了一组API,允许开发者创建、修改...

    java中poi读写excel封装工具类(兼容office2003和2007等版本)

    它不仅支持旧版的Excel文件格式(.xls,用于Office 2003及更早版本),还支持新版本的Excel文件格式(.xlsx,自Office 2007起)。以下是对"java中poi读写excel封装工具类"这一主题的详细解释。 1. **Apache POI介绍...

    POI读写excel文件+poi简单文档

    在这个“POI读写excel文件+poi简单文档”中,我们将深入探讨如何利用Apache POI进行Excel文件的读写操作。 首先,我们需要了解POI的主要组件:HSSF(Horrible Spreadsheet Format)用于处理旧版的BIFF格式(.xls)...

    poi读写excel+poi总结

    Apache POI 是一个开源项目,专门用于处理Microsoft Office格式的文件,包括Excel、Word和PowerPoint等。在本文中,我们将深入探讨如何使用POI进行Excel的读写操作,并进行总结。 1. POI基本概念 Apache POI 提供了...

    POI读写excel(.xls/.xlsx)的Demo

    在这个"POI读写excel(.xls/.xlsx)的Demo"中,我们将深入探讨如何使用Apache POI库在Java中读取和写入Excel文件。 1. **Apache POI库介绍** Apache POI 提供了 HSSF(Horrible Spreadsheet Format)和 XSSF(XML ...

    poi3.9读写excel兼容03和07版本

    "poi3.9读写excel兼容03和07版本"这个标题指的是使用Apache POI 3.9版本的API,能够兼容两种不同格式的Excel文件:.xls(Excel 2003及更早版本)和.xlsx(Excel 2007及更高版本)。 在描述中提到的"完美修订版本...

    apache POI文件读写excel

    - **JExcelAPI**: 一个更简单的库,支持读写Excel文件,但不支持较新的OOXML格式。 - **Apache POI-HSMF**: 用于处理Outlook的MSG文件。 - **Apache POI-OOXML-Schemas**: 提供对OOXML标准的直接访问,用于自定义...

    poi读写office文件样例程序

    这个"poi读写office文件样例程序"提供了一系列的源代码示例,帮助开发者理解和实现对这些文件的读取和写入操作。下面将详细介绍其中涉及的关键知识点。 1. **Apache POI 框架** Apache POI 是Apache软件基金会的一...

    POI操作EXCEL,支持office2003,2007,2010,2013(详)

    这个“POI操作EXCEL,支持office2003,2007,2010,2013(详)”的主题涵盖了一系列知识点,旨在帮助开发者熟练地使用Apache POI处理不同版本的Excel文件。 首先,我们来看Excel的两种主要文件格式:`.xls`(Excel 97-...

    导入poi jar包实现使用Beanshell读写Excel文件

    在Java编程环境中,Apache POI库是一个非常实用的工具,它允许我们操作Microsoft Office格式的文件,特别是Excel(.xls和.xlsx)文件。在JMeter测试框架中,我们可以结合使用POI库和BeanShell组件来读取和写入Excel...

    poi3.1读写excel,wps et

    在本场景中,我们关注的是使用POI 3.1版本来读取和写入Excel以及WPS的ET文件。POI 3.1是一个较旧的版本,但仍然适用于许多基础操作。 首先,让我们深入了解一下Apache POI的基本概念。Apache POI提供了一系列的API...

    Java实现Excel读写的poi 5.2.1版本jar

    OOXML是Excel 2007及以上版本使用的默认文件格式,它以ZIP压缩包的形式存储数据,POI库提供了API来解析和构建这些文件。 `poi-5.2.1.jar`:这是主POI库的JAR,包含了处理HSSF(Horrible Spreadsheet Format)和...

    java用poi读写excel表

    Java中的Apache POI库是一个强大的工具,用于读取、创建和修改Microsoft Office格式的文件,尤其是Excel工作簿。本文将详细介绍如何使用POI库在Java中进行Excel的读写操作,以及一个在Eclipse环境中运行的实例。 ...

    poi读取Excel2007文件

    标题中的“poi读取Excel2007文件”指的是使用Apache POI库来处理Microsoft Office Open XML (OOXML) 格式的Excel文件,也就是.xlsx格式。Apache POI是Apache软件基金会的一个开源项目,它提供了Java API,使得开发者...

    Java用poi读取excel文件

    Java 使用 POI 读取 Excel 文件 Java 是一种广泛使用的编程语言,而 Excel 是一种常用的电子表格软件。有时候,我们需要在 Java 程序中读取 Excel 文件的内容,例如将 Excel 表格中的数据导入到数据库中或者进行...

    poi3.9读写EXCEL

    在本例中,我们将聚焦于“poi3.9读写EXCEL”这一主题,特别是针对支持2007版Excel(XLSX格式)的特性。 Apache POI是Apache软件基金会的一个开源项目,其主要目标是提供一个API,使得Java程序员能够处理Microsoft ...

    poi.zip java读取excel文件

    对于 Excel 文件,POI 使用 HSSF(Horizontally Stored Spreadsheet Format)来处理 .xls 文件(Excel 97-2007 格式),而 XSSF(XML Spreadsheet Format)则用于处理 .xlsx 文件(Excel 2007 及以后版本的格式)。...

    POI读取Excel大文件.rar

    对于Excel,POI支持HSSF(旧的Excel 97-2003格式)和XSSF(新的Excel 2007及以上版本的XML格式)。 2. **读取Excel大文件的挑战** 当处理大容量的Excel文件时,如果直接一次性加载所有数据到内存,可能导致Java...

    POI导入excel大数据处理,支持excel2003,2007

    标题提到的“POI导入excel大数据处理”是指利用Apache POI进行大量Excel数据的导入操作,同时它兼容Excel 2003(.xls格式)和2007以上版本(.xlsx格式)的文件。 POI库的主要优点包括: 1. **多格式支持**:不仅...

    ExcelDemo_Excel导出_下载_POI读excel_JXL读写excel_java读写excel_列宽_读取合并或拆分单元格内容

    总的来说,Java开发者可以通过Apache POI和JExcelAPI轻松地读写Excel文件,进行各种操作,如设置列宽、处理合并或拆分的单元格。理解并熟练掌握这些库,将极大地提升你在处理Excel数据时的效率。在实际项目中,根据...

Global site tag (gtag.js) - Google Analytics