`
runfeel
  • 浏览: 936075 次
文章分类
社区版块
存档分类
最新评论

JAVA 使用POI 读写 excel (for Excel 97-2008)

 
阅读更多

之前用过POI,Jacob,等其他几种方式读取office document,对比之下,还是POI比较靠谱,更新也即时~最近有项目要用,就小小的总结一下~

POI 3.8下载地址http://www.apache.org/dyn/closer.cgi/poi/dev/bin/poi-bin-3.8-beta5-20111217.zip

或者http://poi.apache.org/download.html

/* ====================================================================
   Licensed to the Apache Software Foundation (ASF) under one or more
   contributor license agreements.  See the NOTICE file distributed with
   this work for additional information regarding copyright ownership.
   The ASF licenses this file to You under the Apache License, Version 2.0
   (the "License"); you may not use this file except in compliance with
   the License.  You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
==================================================================== */

package org.apache.poi.hssf.usermodel.examples;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.util.CellRangeAddress;

/**
 * File for HSSF testing/examples
 *
 * THIS IS NOT THE MAIN HSSF FILE!! This is a utility for testing functionality.
 * It does contain sample API usage that may be educational to regular API
 * users.
 *
 * @see #main
 * @author Andrew Oliver (acoliver at apache dot org)
 */
public final class HSSFReadWrite {

	/**
	 * creates an {@link HSSFWorkbook} the specified OS filename.
	 */
	private static HSSFWorkbook readFile(String filename) throws IOException {
		return new HSSFWorkbook(new FileInputStream(filename));
	}

	/**
	 * given a filename this outputs a sample sheet with just a set of
	 * rows/cells.
	 */
	private static void testCreateSampleSheet(String outputFilename) throws IOException {
		int rownum;
		HSSFWorkbook wb = new HSSFWorkbook();
		HSSFSheet s = wb.createSheet();
		HSSFCellStyle cs = wb.createCellStyle();
		HSSFCellStyle cs2 = wb.createCellStyle();
		HSSFCellStyle cs3 = wb.createCellStyle();
		HSSFFont f = wb.createFont();
		HSSFFont f2 = wb.createFont();

		f.setFontHeightInPoints((short) 12);
		f.setColor((short) 0xA);
		f.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
		f2.setFontHeightInPoints((short) 10);
		f2.setColor((short) 0xf);
		f2.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
		cs.setFont(f);
		cs.setDataFormat(HSSFDataFormat.getBuiltinFormat("($#,##0_);[Red]($#,##0)"));
		cs2.setBorderBottom(HSSFCellStyle.BORDER_THIN);
		cs2.setFillPattern((short) 1); // fill w fg
		cs2.setFillForegroundColor((short) 0xA);
		cs2.setFont(f2);
		wb.setSheetName(0, "HSSF Test");
		for (rownum = 0; rownum < 300; rownum++) {
			HSSFRow r = s.createRow(rownum);
			if ((rownum % 2) == 0) {
				r.setHeight((short) 0x249);
			}

			for (int cellnum = 0; cellnum < 50; cellnum += 2) {
				HSSFCell c = r.createCell(cellnum);
				c.setCellValue(rownum * 10000 + cellnum
						+ (((double) rownum / 1000) + ((double) cellnum / 10000)));
				if ((rownum % 2) == 0) {
					c.setCellStyle(cs);
				}
				c = r.createCell(cellnum + 1);
				c.setCellValue(new HSSFRichTextString("TEST"));
				// 50 characters divided by 1/20th of a point
				s.setColumnWidth(cellnum + 1, (int) (50 * 8 / 0.05));
				if ((rownum % 2) == 0) {
					c.setCellStyle(cs2);
				}
			}
		}

		// draw a thick black border on the row at the bottom using BLANKS
		rownum++;
		rownum++;
		HSSFRow r = s.createRow(rownum);
		cs3.setBorderBottom(HSSFCellStyle.BORDER_THICK);
		for (int cellnum = 0; cellnum < 50; cellnum++) {
			HSSFCell c = r.createCell(cellnum);
			c.setCellStyle(cs3);
		}
		s.addMergedRegion(new CellRangeAddress(0, 3, 0, 3));
		s.addMergedRegion(new CellRangeAddress(100, 110, 100, 110));

		// end draw thick black border
		// create a sheet, set its title then delete it
		s = wb.createSheet();
		wb.setSheetName(1, "DeletedSheet");
		wb.removeSheetAt(1);

		// end deleted sheet
		FileOutputStream out = new FileOutputStream(outputFilename);
		wb.write(out);
		out.close();
	}

	/**
     * Method main
     *
     * Given 1 argument takes that as the filename, inputs it and dumps the
     * cell values/types out to sys.out.<br/>
     *
     * given 2 arguments where the second argument is the word "write" and the
     * first is the filename - writes out a sample (test) spreadsheet
     * see {@link HSSFReadWrite#testCreateSampleSheet(String)}.<br/>
     *
     * given 2 arguments where the first is an input filename and the second
     * an output filename (not write), attempts to fully read in the
     * spreadsheet and fully write it out.<br/>
     *
     * given 3 arguments where the first is an input filename and the second an
     * output filename (not write) and the third is "modify1", attempts to read in the
     * spreadsheet, deletes rows 0-24, 74-99.  Changes cell at row 39, col 3 to
     * "MODIFIED CELL" then writes it out.  Hence this is "modify test 1".  If you
     * take the output from the write test, you'll have a valid scenario.
     */
	public static void main(String[] args) {
		if (args.length < 1) {
			System.err.println("At least one argument expected");
			return;
		}

		String fileName = args[0];
		try {
			if (args.length < 2) {

				HSSFWorkbook wb = HSSFReadWrite.readFile(fileName);

				System.out.println("Data dump:\n");

				for (int k = 0; k < wb.getNumberOfSheets(); k++) {
					HSSFSheet sheet = wb.getSheetAt(k);
					int rows = sheet.getPhysicalNumberOfRows();
					System.out.println("Sheet " + k + " \"" + wb.getSheetName(k) + "\" has " + rows
							+ " row(s).");
					for (int r = 0; r < rows; r++) {
						HSSFRow row = sheet.getRow(r);
						if (row == null) {
							continue;
						}

						int cells = row.getPhysicalNumberOfCells();
						System.out.println("\nROW " + row.getRowNum() + " has " + cells
								+ " cell(s).");
						for (int c = 0; c < cells; c++) {
							HSSFCell cell = row.getCell(c);
							String value = null;

							switch (cell.getCellType()) {

								case HSSFCell.CELL_TYPE_FORMULA:
									value = "FORMULA value=" + cell.getCellFormula();
									break;

								case HSSFCell.CELL_TYPE_NUMERIC:
									value = "NUMERIC value=" + cell.getNumericCellValue();
									break;

								case HSSFCell.CELL_TYPE_STRING:
									value = "STRING value=" + cell.getStringCellValue();
									break;

								default:
							}
							System.out.println("CELL col=" + cell.getColumnIndex() + " VALUE="
									+ value);
						}
					}
				}
			} else if (args.length == 2) {
				if (args[1].toLowerCase().equals("write")) {
					System.out.println("Write mode");
					long time = System.currentTimeMillis();
					HSSFReadWrite.testCreateSampleSheet(fileName);

					System.out.println("" + (System.currentTimeMillis() - time)
							+ " ms generation time");
				} else {
					System.out.println("readwrite test");
					HSSFWorkbook wb = HSSFReadWrite.readFile(fileName);
					FileOutputStream stream = new FileOutputStream(args[1]);

					wb.write(stream);
					stream.close();
				}
			} else if (args.length == 3 && args[2].toLowerCase().equals("modify1")) {
				// delete row 0-24, row 74 - 99 && change cell 3 on row 39 to string "MODIFIED CELL!!"

				HSSFWorkbook wb = HSSFReadWrite.readFile(fileName);
				FileOutputStream stream = new FileOutputStream(args[1]);
				HSSFSheet sheet = wb.getSheetAt(0);

				for (int k = 0; k < 25; k++) {
					HSSFRow row = sheet.getRow(k);

					sheet.removeRow(row);
				}
				for (int k = 74; k < 100; k++) {
					HSSFRow row = sheet.getRow(k);

					sheet.removeRow(row);
				}
				HSSFRow row = sheet.getRow(39);
				HSSFCell cell = row.getCell(3);
				cell.setCellValue("MODIFIED CELL!!!!!");

				wb.write(stream);
				stream.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}


分享到:
评论

相关推荐

    poi-3.9、poi-ooxml-3.9、poi-ooxml-schemas-3.9

    HSSF是用于读写旧的BIFF格式(Excel 97-2007),而XSSF则是用于处理新的OOXML格式(Excel 2007及以后版本)。 2. poi-ooxml-3.9.jar:这个库提供了对Office Open XML (OOXML) 格式的额外支持。OOXML是微软推出的一...

    poi全家桶ooxml-schemas/poi/poi-examples/poi-ooxml/poi-ooxml-schemas/poi-scratchpad

    Apache POI是一个开源的Java库,专门用于读写Microsoft Office格式的文件,特别是Excel、Word和PowerPoint文档。在提供的描述中,我们看到的路径实际上是在指示Apache POI项目中的不同模块和示例代码的位置。 1. **...

    java用poi读写excel表

    本文将详细介绍如何使用POI库在Java中进行Excel的读写操作,以及一个在Eclipse环境中运行的实例。 首先,我们需要了解Apache POI的基本概念。POI是Apache软件基金会的一个开源项目,它提供了Java API来处理...

    java使用poi读写excel

    Java使用Apache POI读写Excel是常见的数据处理任务,尤其在数据分析、报表生成等领域中广泛应用。Apache POI是一个开源库,允许程序员创建、修改和显示Microsoft Office格式的文件,其中包括Excel(XLS和XLSX)文件...

    poi-3.12-android-a.jar和poi-ooxml-schemas-3.12-20150511-a.jar

    Apache POI是一个流行的Java库,允许程序员创建、修改和显示MS Office文件,包括Excel工作簿。这个特定的.jar文件包含了基本的功能以支持.xls格式的Excel文件操作。 poi-ooxml-schemas-3.12-20150511-a.jar: 这个库...

    poi读写excel+poi总结

    在本文中,我们将深入探讨如何使用POI进行Excel的读写操作,并进行总结。 1. POI基本概念 Apache POI 提供了HSSF(Horrible Spreadsheet Format)用于读写旧版的.xls格式的Excel文件,而XSSF则用于处理.xlsx格式的...

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

    以下是对"java中poi读写excel封装工具类"这一主题的详细解释。 1. **Apache POI介绍** Apache POI是一个开源项目,允许Java开发者创建、修改和显示Microsoft Office文件,包括Excel、Word和PowerPoint。它的核心...

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

    Java中的Apache POI库是一个强大的工具,用于读取和写入Microsoft Office格式的文件,特别是Excel的XLS和XLSX格式。在这个5.2.1版本中,POI提供了对Excel电子表格的强大支持,包括读取数据、修改内容、创建新工作簿...

    java poi 读写excel

    遗憾的是,提供的文件列表中只有`jeebbs-db-3.sql`,这似乎是一个SQL数据库文件,与Java POI读写Excel的主题并不直接相关。通常,SQL文件用于导入或导出数据库的数据,如果博客作者有提到结合Java POI与SQL操作Excel...

    poi的所有jar包,poi, poi-ooxml,poi-ooxml-schemas的各个版本jar

    Apache POI 是一个开源项目,专门用于...总的来说,Apache POI是Java开发中不可或缺的一个工具,它极大地拓宽了Java处理Microsoft Office文件的能力,让开发者能够在不依赖于Office软件的情况下实现文件的读写和操作。

    java excel操作 poi-3.17 可用于jdk1.70

    附件是java poi 3.17的lib库及其依赖库,全部下载引用后,可以进行excel的读写操作,无需引用其他lib库。poi-3.17适用于jdk1.7。 Apache POI是Apache软件基金会的开放源码函式库,POI提供API给Java程序对Microsoft ...

    java的poi读写excel项目实例

    在这个“java的poi读写excel项目实例”中,我们有两个主要的Java类:`read.java`和`write.java`,分别用于处理Excel文件的读取和写入操作。 首先,让我们深入了解一下`read.java`。这个类通常会包含一个方法,比如`...

    apache POI文件读写excel

    Apache POI是Java领域中广泛使用的库,专为处理Microsoft Office格式的文件而设计,特别是Excel文档。这个库使得在不依赖Microsoft Office的情况下,开发者能够读取、创建、修改和操作XLS、XLSX等Excel文件。在本文...

    java Excel文件 poi-bin-3.1-FINAL-20080629

    Java Excel文件处理主要依赖于Apache POI库,这是一个开源项目,专门用于读写...总之,Apache POI是Java开发者处理Excel文件的强大工具,通过学习和使用这个库,可以轻松地在Java应用程序中集成Excel数据的读写功能。

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

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

    java导出excel POI jar包

    Apache POI库是Java领域中广泛使用的工具,它允许开发者读写Microsoft Office格式的文件,包括Excel(.xlsx和.xls)。本篇文章将深入讲解如何使用POI库在Java中实现Excel的导出功能,以及涉及到的相关jar包及其作用...

    POI操作Excel----------(转人家的)

    Apache POI 是一个Java库,专门用于读写Microsoft Office格式的文件,特别是Excel(.xls)文件。在本文中,我们将深入探讨如何使用POI进行Excel操作,以及库中的关键概念和类。 首先,要使用POI,你需要从官方网站...

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

    总的来说,“POI读写excel文件+poi简单文档”涵盖了Apache POI在Java环境中处理Excel文件的基础和进阶知识,是学习和使用POI进行Excel操作的重要参考资料。通过学习和实践,开发者可以轻松地在Java程序中实现Excel...

    java使用POI操作excel (支持excel2007)

    Java 使用Apache POI库操作Excel 2007文件详解 在Java开发中,处理Excel文件是一项常见的任务,特别是对于数据分析、数据导入导出或报表生成等场景。Apache POI是一个流行的开源库,它允许开发者读写Microsoft ...

Global site tag (gtag.js) - Google Analytics