`
jetway
  • 浏览: 480281 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
社区版块
存档分类
最新评论

JAVA用POI读取和创建2003和2007版本Excel完美示例

 
阅读更多

<!--[if !supportEmptyParas]--> <!--[endif]-->

<!--[if !supportEmptyParas]--> <!--[endif]-->

import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import java.text.DecimalFormat;

import java.text.SimpleDateFormat;

import java.util.Date;

import java.util.LinkedList;

import java.util.List;

<!--[if !supportEmptyParas]--> <!--[endif]-->

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.HSSFDateUtil;

import org.apache.poi.hssf.usermodel.HSSFFont;

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.hssf.util.HSSFColor;

import org.apache.poi.xssf.usermodel.XSSFCell;

import org.apache.poi.xssf.usermodel.XSSFCellStyle;

import org.apache.poi.xssf.usermodel.XSSFFont;

import org.apache.poi.xssf.usermodel.XSSFRow;

import org.apache.poi.xssf.usermodel.XSSFSheet;

import org.apache.poi.xssf.usermodel.XSSFWorkbook;

<!--[if !supportEmptyParas]--> <!--[endif]-->

/**

 * 可以从http://poi.apache.org/ 这里下载到POI的jar包 POI

创建和读取2003-2007版本Excel文件

 *

 */

<!--[if !supportEmptyParas]--> <!--[endif]-->

public class CreatAndReadExcel {

<!--[if !supportEmptyParas]--> <!--[endif]-->

public static void main(String[] args) throws Exception {

<!--[if !supportEmptyParas]--> <!--[endif]-->

creat2003Excel();// 创建2007版Excel文件

creat2007Excel();// 创建2003版Excel文件

//读取2003Excel文件

String path2003 = System.getProperty("user.dir")

+ System.getProperty("file.separator") + "style_2003.xls";// 获取项目文件路径

+2003版文件名

System.out.println("路径:" + path2003);

File f2003 = new File(path2003);

try {

readExcel(f2003);

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

        //读取2007Excel文件

String path2007 = System.getProperty("user.dir")

+ System.getProperty("file.separator") + "style_2007.xlsx";// 获取项目文件路径

+2007版文件名

System.out.println("路径:" + path2007);

File f2007 = new File(path2007);

try {

readExcel(f2007);

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

<!--[if !supportEmptyParas]--> <!--[endif]-->

}

<!--[if !supportEmptyParas]--> <!--[endif]-->

/**

* 创建2007版Excel文件

*

* @throws FileNotFoundException

* @throws IOException

*/

private static void creat2007Excel() throws FileNotFoundException,

IOException {

// HSSFWorkbook workBook = new HSSFWorkbook();// 创建 一个excel文档对象

XSSFWorkbook workBook = new XSSFWorkbook();

XSSFSheet sheet = workBook.createSheet();// 创建一个工作薄对象

<!--[if !supportEmptyParas]--> <!--[endif]-->

sheet.setColumnWidth(1, 10000);// 设置第二列的宽度为

<!--[if !supportEmptyParas]--> <!--[endif]-->

XSSFRow row = sheet.createRow(1);// 创建一个行对象

<!--[if !supportEmptyParas]--> <!--[endif]-->

row.setHeightInPoints(23);// 设置行高23像素

<!--[if !supportEmptyParas]--> <!--[endif]-->

XSSFCellStyle style = workBook.createCellStyle();// 创建样式对象

<!--[if !supportEmptyParas]--> <!--[endif]-->

// 设置字体

<!--[if !supportEmptyParas]--> <!--[endif]-->

XSSFFont font = workBook.createFont();// 创建字体对象

<!--[if !supportEmptyParas]--> <!--[endif]-->

font.setFontHeightInPoints((short) 15);// 设置字体大小

<!--[if !supportEmptyParas]--> <!--[endif]-->

font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);// 设置粗体

<!--[if !supportEmptyParas]--> <!--[endif]-->

font.setFontName("黑体");// 设置为黑体字

<!--[if !supportEmptyParas]--> <!--[endif]-->

style.setFont(font);// 将字体加入到样式对象

<!--[if !supportEmptyParas]--> <!--[endif]-->

// 设置对齐方式

<!--[if !supportEmptyParas]--> <!--[endif]-->

style.setAlignment(HSSFCellStyle.ALIGN_CENTER_SELECTION);// 水平居中

<!--[if !supportEmptyParas]--> <!--[endif]-->

style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 垂直居中

<!--[if !supportEmptyParas]--> <!--[endif]-->

// 设置边框

<!--[if !supportEmptyParas]--> <!--[endif]-->

style.setBorderTop(HSSFCellStyle.BORDER_THICK);// 顶部边框粗线

<!--[if !supportEmptyParas]--> <!--[endif]-->

style.setTopBorderColor(HSSFColor.RED.index);// 设置为红色

<!--[if !supportEmptyParas]--> <!--[endif]-->

style.setBorderBottom(HSSFCellStyle.BORDER_DOUBLE);// 底部边框双线

<!--[if !supportEmptyParas]--> <!--[endif]-->

style.setBorderLeft(HSSFCellStyle.BORDER_MEDIUM);// 左边边框

<!--[if !supportEmptyParas]--> <!--[endif]-->

style.setBorderRight(HSSFCellStyle.BORDER_MEDIUM);// 右边边框

<!--[if !supportEmptyParas]--> <!--[endif]-->

// 格式化日期

<!--[if !supportEmptyParas]--> <!--[endif]-->

style.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy h:mm"));

<!--[if !supportEmptyParas]--> <!--[endif]-->

XSSFCell cell = row.createCell(1);// 创建单元格

<!--[if !supportEmptyParas]--> <!--[endif]-->

cell.setCellValue(new Date());// 写入当前日期

<!--[if !supportEmptyParas]--> <!--[endif]-->

cell.setCellStyle(style);// 应用样式对象

<!--[if !supportEmptyParas]--> <!--[endif]-->

// 文件输出流

<!--[if !supportEmptyParas]--> <!--[endif]-->

FileOutputStream os = new FileOutputStream("style_2007.xlsx");

<!--[if !supportEmptyParas]--> <!--[endif]-->

workBook.write(os);// 将文档对象写入文件输出流

<!--[if !supportEmptyParas]--> <!--[endif]-->

os.close();// 关闭文件输出流

System.out.println("创建成功 office 2007 excel");

}

<!--[if !supportEmptyParas]--> <!--[endif]-->

/**

* 创建2003版本的Excel文件

*/

private static void creat2003Excel() throws FileNotFoundException,

IOException {

HSSFWorkbook workBook = new HSSFWorkbook();// 创建 一个excel文档对象

<!--[if !supportEmptyParas]--> <!--[endif]-->

HSSFSheet sheet = workBook.createSheet();// 创建一个工作薄对象

<!--[if !supportEmptyParas]--> <!--[endif]-->

sheet.setColumnWidth(1, 10000);// 设置第二列的宽度为

<!--[if !supportEmptyParas]--> <!--[endif]-->

HSSFRow row = sheet.createRow(1);// 创建一个行对象

<!--[if !supportEmptyParas]--> <!--[endif]-->

row.setHeightInPoints(23);// 设置行高23像素

<!--[if !supportEmptyParas]--> <!--[endif]-->

HSSFCellStyle style = workBook.createCellStyle();// 创建样式对象

<!--[if !supportEmptyParas]--> <!--[endif]-->

// 设置字体

<!--[if !supportEmptyParas]--> <!--[endif]-->

HSSFFont font = workBook.createFont();// 创建字体对象

<!--[if !supportEmptyParas]--> <!--[endif]-->

font.setFontHeightInPoints((short) 15);// 设置字体大小

<!--[if !supportEmptyParas]--> <!--[endif]-->

font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);// 设置粗体

<!--[if !supportEmptyParas]--> <!--[endif]-->

font.setFontName("黑体");// 设置为黑体字

<!--[if !supportEmptyParas]--> <!--[endif]-->

style.setFont(font);// 将字体加入到样式对象

<!--[if !supportEmptyParas]--> <!--[endif]-->

// 设置对齐方式

<!--[if !supportEmptyParas]--> <!--[endif]-->

style.setAlignment(HSSFCellStyle.ALIGN_CENTER_SELECTION);// 水平居中

<!--[if !supportEmptyParas]--> <!--[endif]-->

style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 垂直居中

<!--[if !supportEmptyParas]--> <!--[endif]-->

// 设置边框

<!--[if !supportEmptyParas]--> <!--[endif]-->

style.setBorderTop(HSSFCellStyle.BORDER_THICK);// 顶部边框粗线

<!--[if !supportEmptyParas]--> <!--[endif]-->

style.setTopBorderColor(HSSFColor.RED.index);// 设置为红色

<!--[if !supportEmptyParas]--> <!--[endif]-->

style.setBorderBottom(HSSFCellStyle.BORDER_DOUBLE);// 底部边框双线

<!--[if !supportEmptyParas]--> <!--[endif]-->

style.setBorderLeft(HSSFCellStyle.BORDER_MEDIUM);// 左边边框

<!--[if !supportEmptyParas]--> <!--[endif]-->

style.setBorderRight(HSSFCellStyle.BORDER_MEDIUM);// 右边边框

<!--[if !supportEmptyParas]--> <!--[endif]-->

// 格式化日期

<!--[if !supportEmptyParas]--> <!--[endif]-->

style.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy h:mm"));

<!--[if !supportEmptyParas]--> <!--[endif]-->

HSSFCell cell = row.createCell(1);// 创建单元格

<!--[if !supportEmptyParas]--> <!--[endif]-->

cell.setCellValue(new Date());// 写入当前日期

<!--[if !supportEmptyParas]--> <!--[endif]-->

cell.setCellStyle(style);// 应用样式对象

<!--[if !supportEmptyParas]--> <!--[endif]-->

// 文件输出流

<!--[if !supportEmptyParas]--> <!--[endif]-->

FileOutputStream os = new FileOutputStream("style_2003.xls");

<!--[if !supportEmptyParas]--> <!--[endif]-->

workBook.write(os);// 将文档对象写入文件输出流

<!--[if !supportEmptyParas]--> <!--[endif]-->

os.close();// 关闭文件输出流

System.out.println("创建成功 office 2003 excel");

}

<!--[if !supportEmptyParas]--> <!--[endif]-->

/**

* 对外提供读取excel 的方法

*/

public static List<List<Object>> readExcel(File file) throws IOException {

String fileName = file.getName();

String extension = fileName.lastIndexOf(".") == -1 ? "" : fileName

.substring(fileName.lastIndexOf(".") + 1);

if ("xls".equals(extension)) {

return read2003Excel(file);

} else if ("xlsx".equals(extension)) {

return read2007Excel(file);

} else {

throw new IOException("不支持的文件类型");

}

}

<!--[if !supportEmptyParas]--> <!--[endif]-->

/**

* 读取 office 2003 excel

*

* @throws IOException

* @throws FileNotFoundException

*/

private static List<List<Object>> read2003Excel(File file)

throws IOException {

List<List<Object>> list = new LinkedList<List<Object>>();

HSSFWorkbook hwb = new HSSFWorkbook(new FileInputStream(file));

HSSFSheet sheet = hwb.getSheetAt(0);

Object value = null;

HSSFRow row = null;

HSSFCell cell = null;

System.out.println("读取office 2003 excel内容如下:");

for (int i = sheet.getFirstRowNum(); i <= sheet

.getPhysicalNumberOfRows(); i++) {

row = sheet.getRow(i);

if (row == null) {

continue;

}

List<Object> linked = new LinkedList<Object>();

for (int j = row.getFirstCellNum(); j <= row.getLastCellNum(); j++) {

cell = row.getCell(j);

if (cell == null) {

continue;

}

DecimalFormat df = new DecimalFormat("0");// 格式化 number String

// 字符

SimpleDateFormat sdf = new SimpleDateFormat(

"yyyy-MM-dd HH:mm:ss");// 格式化日期字符串

DecimalFormat nf = new DecimalFormat("0.00");// 格式化数字

switch (cell.getCellType()) {

case XSSFCell.CELL_TYPE_STRING:

// System.out.println(i + "行" + j + " 列 is String type");

value = cell.getStringCellValue();

System.out.print("  " + value + "  ");

break;

case XSSFCell.CELL_TYPE_NUMERIC:

// System.out.println(i + "行" + j

// + " 列 is Number type ; DateFormt:"

// + cell.getCellStyle().getDataFormatString());

if ("@".equals(cell.getCellStyle().getDataFormatString())) {

value = df.format(cell.getNumericCellValue());

<!--[if !supportEmptyParas]--> <!--[endif]-->

} else if ("General".equals(cell.getCellStyle()

.getDataFormatString())) {

value = nf.format(cell.getNumericCellValue());

} else {

value = sdf.format(HSSFDateUtil.getJavaDate(cell

.getNumericCellValue()));

}

System.out.print("  " + value + "  ");

break;

case XSSFCell.CELL_TYPE_BOOLEAN:

// System.out.println(i + "行" + j + " 列 is Boolean type");

value = cell.getBooleanCellValue();

System.out.print("  " + value + "  ");

break;

case XSSFCell.CELL_TYPE_BLANK:

// System.out.println(i + "行" + j + " 列 is Blank type");

value = "";

System.out.print("  " + value + "  ");

break;

default:

// System.out.println(i + "行" + j + " 列 is default type");

value = cell.toString();

System.out.print("  " + value + "  ");

}

if (value == null || "".equals(value)) {

continue;

}

linked.add(value);

<!--[if !supportEmptyParas]--> <!--[endif]-->

}

System.out.println("");

list.add(linked);

}

<!--[if !supportEmptyParas]--> <!--[endif]-->

return list;

}

<!--[if !supportEmptyParas]--> <!--[endif]-->

/**

* 读取Office 2007 excel

*/

<!--[if !supportEmptyParas]--> <!--[endif]-->

private static List<List<Object>> read2007Excel(File file)

throws IOException {

<!--[if !supportEmptyParas]--> <!--[endif]-->

List<List<Object>> list = new LinkedList<List<Object>>();

// String path = System.getProperty("user.dir") +

// System.getProperty("file.separator")+"dd.xlsx";

// System.out.println("路径:"+path);

// 构造 XSSFWorkbook 对象,strPath 传入文件路径

XSSFWorkbook xwb = new XSSFWorkbook(new FileInputStream(file));

<!--[if !supportEmptyParas]--> <!--[endif]-->

// 读取第一章表格内容

XSSFSheet sheet = xwb.getSheetAt(0);

Object value = null;

XSSFRow row = null;

XSSFCell cell = null;

System.out.println("读取office 2007 excel内容如下:");

for (int i = sheet.getFirstRowNum(); i <= sheet

.getPhysicalNumberOfRows(); i++) {

row = sheet.getRow(i);

if (row == null) {

continue;

}

List<Object> linked = new LinkedList<Object>();

for (int j = row.getFirstCellNum(); j <= row.getLastCellNum(); j++) {

cell = row.getCell(j);

if (cell == null) {

continue;

}

DecimalFormat df = new DecimalFormat("0");// 格式化 number String

// 字符

SimpleDateFormat sdf = new SimpleDateFormat(

"yyyy-MM-dd HH:mm:ss");// 格式化日期字符串

DecimalFormat nf = new DecimalFormat("0.00");// 格式化数字

<!--[if !supportEmptyParas]--> <!--[endif]-->

switch (cell.getCellType()) {

case XSSFCell.CELL_TYPE_STRING:

// System.out.println(i + "行" + j + " 列 is String type");

value = cell.getStringCellValue();

System.out.print("  " + value + "  ");

break;

case XSSFCell.CELL_TYPE_NUMERIC:

// System.out.println(i + "行" + j

// + " 列 is Number type ; DateFormt:"

// + cell.getCellStyle().getDataFormatString());

if ("@".equals(cell.getCellStyle().getDataFormatString())) {

value = df.format(cell.getNumericCellValue());

<!--[if !supportEmptyParas]--> <!--[endif]-->

} else if ("General".equals(cell.getCellStyle()

.getDataFormatString())) {

value = nf.format(cell.getNumericCellValue());

} else {

value = sdf.format(HSSFDateUtil.getJavaDate(cell

.getNumericCellValue()));

}

System.out.print("  " + value + "  ");

break;

case XSSFCell.CELL_TYPE_BOOLEAN:

// System.out.println(i + "行" + j + " 列 is Boolean type");

value = cell.getBooleanCellValue();

System.out.print("  " + value + "  ");

break;

case XSSFCell.CELL_TYPE_BLANK:

// System.out.println(i + "行" + j + " 列 is Blank type");

value = "";

// System.out.println(value);

break;

default:

// System.out.println(i + "行" + j + " 列 is default type");

value = cell.toString();

System.out.print("  " + value + "  ");

}

if (value == null || "".equals(value)) {

continue;

}

linked.add(value);

}

System.out.println("");

list.add(linked);

}

return list;

}

}

分享到:
评论

相关推荐

    JAVA用POI读取和创建2003和2007版本Excel完美示例.pdf

    本示例代码展示了如何使用POI处理2003和2007版本的Excel文件。 1. **创建2003版Excel文件(`.xls`)** 使用`HSSFWorkbook`类来创建2003版Excel文件。以下是一些关键点: - `HSSFWorkbook`:这是处理Excel 97-...

    JAVA用POI读取和创建2003和2007版本Excel完美示例.docx

    在这个示例中,我们看到如何使用 POI 库来读取和创建 2003 和 2007 版本的 Excel 文件。 1. **POI 库的导入**: 示例代码导入了多个 POI 相关的类,包括 HSSF 和 XSSF 前缀的类。HSSF 用于处理 .xls(Excel 97-...

    Java解析Excel兼容2003和2007(有实例和类包)

    提供的文档"JAVA用POI读取和创建2003和2007版本Excel完美示例.docx"应该包含完整的代码示例,展示了如何使用POI读取和创建不同版本的Excel文件。你可以参考这个文档来了解具体的实现细节。 总之,Apache POI是Java...

    java用poi读取和创建excel

    - **公式和图表**:POI也支持创建和解析Excel的公式,以及插入图表,但较为复杂。 - **事件模型**:对于大文件,可以使用SXSSF,这是一个内存效率更高的API,它基于事件模型,只保存最近使用的行。 6. **最佳实践...

    java poi导出图片到excel示例代码

    Java POI导出图片到Excel示例代码详解 Java POI是Java开发中常用的开源库,用于读写Microsoft Office文件格式,包括Excel、Word、PowerPoint等。今天,我们将介绍如何使用Java POI将图片导出到Excel中。 标题解释 ...

    java的poi生成excel图表demo

    Java的Apache POI库是一个强大的工具,用于读取、创建和修改Microsoft Office格式的文件,尤其是Excel(.xlsx)文档。在本示例中,我们将深入探讨如何利用POI库来生成Excel中的图表曲线,这对于数据可视化和报告生成...

    Java用poi读取excel文件

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

    java_poi实现excel导入导出

    Java POI 实现 Excel 导入导出 Java POI 是一个流行的 Java 库,用于处理 Microsoft Office 文件格式,包括 ...在本文中,我们已经详细介绍了如何使用 Java POI 实现 Excel 导入导出功能,包括读取和写入 Excel 文件。

    java用poi解析excel2003和2007并封装成对象返回

    Java使用Apache POI库解析Excel 2003(.xls)和2007(.xlsx)文件是一项常见的任务,特别是在数据导入、数据分析或自动化处理场景中。Apache POI是一个开源项目,提供了读写Microsoft Office格式文件的能力,包括...

    java POI完整示例,POI将word转HTML,数据库倒出数据到Excel等

    它支持HSSF(Horizontally SpreadSheet Format)用于处理Excel 97-2003的`.xls`文件,XSSF(XML Spreadsheet Format)用于处理Excel 2007及更高版本的`.xlsx`文件,以及HWPF(Horizontally Written Portable ...

    java使用POI读取和导出Excel

    这两个API提供了对工作簿(Workbook)、工作表(Sheet)、行(Row)和单元格(Cell)的创建、读取和修改功能。 **读取Excel文件** 读取Excel文件的基本步骤如下: 1. 引入POI依赖:在你的Maven或Gradle项目中,...

    poi 解析 office excel 2003,2007 word 2003,2007 的示例

    本示例将详细介绍如何使用Apache POI解析Office Excel 2003和2007,以及Word 2003和2007的文件。 首先,我们来看Excel的解析。Excel 2003使用的是.BOOK文件格式(HSSFWorkbook),而2007及以上版本使用的是.XLSX...

    Java用poi读取excel文件.pdf

    2. 使用 `POIFSFileSystem` 类打开文件系统,这是 POI 用来读取老版本(97-2003 格式)Excel 文件的方式。 ```java POIFSFileSystem fs = new POIFSFileSystem(input); ``` 3. 创建 `HSSFWorkbook` 对象,表示整个...

    java通过poi解析Excel示例

    此外,POI还支持对Excel进行更复杂的操作,如创建新的工作表、合并单元格、设置样式和公式等。如果你需要处理的Excel文件包含复杂的数据结构,例如表头、多级索引或公式计算,你需要了解更多的API和方法。 在实际...

    Java通过POI读取Excel遍历数据,批量生成word文档

    Apache POI是一个开源项目,它允许Java开发者处理Microsoft Office格式的文件,如Excel(.xlsx或.xls)和Word(.docx)。 首先,我们需要导入Apache POI的相关依赖。在Maven项目中,可以在pom.xml文件中添加以下...

    java读取excel poi 方法

    #### 二、Java中使用POI读取Excel的关键概念 在 Java 中使用 POI 读取 Excel 文件,首先需要理解以下几个关键的概念: - **Workbook**: 表示整个 Excel 文件,可以包含一个或多个 Sheet。 - **Sheet**: 工作表,每...

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

    在这个5.2.1版本中,POI提供了对Excel电子表格的强大支持,包括读取数据、修改内容、创建新工作簿以及处理复杂的公式和样式。 `poi-ooxml-lite-5.2.1.jar`:这个轻量级的JAR文件包含了处理OOXML(Office Open XML)...

    poi读取excel2007和2003兼容工具例子

    在这个"poi读取excel2007和2003兼容工具例子"中,我们将探讨如何使用POI来读取不同版本的Excel文件,特别是Excel 2003(.xls)和Excel 2007及更高版本(.xlsx)。 1. **Apache POI库**:Apache POI是Apache软件基金...

Global site tag (gtag.js) - Google Analytics