接下来介绍一下采用java操作excel的第三方框架:poi,对于poi,我想搞过批量导入、导出数据的博友都应该熟悉(当然啦,批量导入导出excel数据还有jxl,这里我就不介绍了!)。poi是apache jakarta项目的子项目,主要的用途在于提供一组用于操作windows 文档的java api,如操作word,excel,powerpoint等,详细介绍诸位博友可以看看其他的网络介绍。(其中,SSM版本的POI导入导出我也整理成了博文以及视频教程:

    本篇博文将介绍一下采用poi读写excel,为后续介绍的批量导入、导出excel数据做铺垫!

    工欲善其事,必先利其器。首先,需要poi的Jar包,就一个而已,可以到官网下,也可以来我这里:poi操作excel需要的jar  ,除此之外,就是需要对excel的基本一些知识需要有所了解,如sheet,row,cell等概念。最后需要明确一点:先有excel文件(工作簿),再有sheet,再有row,最后才有cell,明确了这一点,其实在操作excel上已经迈出了第一步!

    废话不多说,直接上代码吧,代码中我已经有所注释,如果需要扩展功能,可以去查看poi的相关api,或者去网上下载一些pdf、word文档来瞧瞧。我找了一篇,没全看完,但是觉得还行,可以来我这里下载:java之poi操作excel实战文档

    下面是我建立的jar project的总体图:这里,我只介绍ExcelRead和ExcelWrite,即excel读写操作。

JAVA POI设置单元格居中 java poi操作excel_excel

 

    下面是ExcelWrite:

 

package com.poi.second;

import java.io.FileOutputStream;
import java.util.Date;

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.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CreationHelper;

/**
 * 写excel
 * @author 钟林森
 *
 */
public class ExcelWrite {
	public static void main(String[] args) throws Exception{
		
		//创建一个工作簿 即excel文件,再在该文件中创建一个sheet
		HSSFWorkbook wb=new HSSFWorkbook();
		HSSFSheet sheet=wb.createSheet("第一个sheet");
		
		//在sheet中创建一行
		HSSFRow row=sheet.createRow(0);
		
		//在该行写入各种类型的数据
		row.createCell(0).setCellValue(true);
		row.createCell(1).setCellValue("钟林森");
		row.createCell(2).setCellValue(23);
		
		//设置保留两位小数
		HSSFCell cell=row.createCell(3);
	        cell.setCellValue(6000);
                HSSFCellStyle cellStyle = wb.createCellStyle();
                cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("0.00"));
                cell.setCellStyle(cellStyle);
		
		//在写入 日期格式的 数据需要进行特殊处理(这是一种 简单的处理方式)
		CreationHelper createHelper=wb.getCreationHelper();
		HSSFCellStyle style=wb.createCellStyle();
		style.setDataFormat(createHelper.createDataFormat().getFormat("yyyy-MM-dd"));
		
		cell=row.createCell(4);
		cell.setCellValue(new Date());
		cell.setCellStyle(style);
		
		//最后写回磁盘
		FileOutputStream out=new FileOutputStream("E:\\java_BasicWeb\\someFiles\\excel写数据.xls");
		wb.write(out);
		out.close();
		
		System.out.println("写完了!");
	}
}

    我们看写回磁盘的那个 “excel写数据.xls”文件:

 

JAVA POI设置单元格居中 java poi操作excel_excel读写操作_02

 

    打开来看一下:成功写入

JAVA POI设置单元格居中 java poi操作excel_excel_03

 

   接下来,我们来读取excel文件,刚刚写入的那个磁盘的“excel读数据.xls”,打开先来看一下:

JAVA POI设置单元格居中 java poi操作excel_poi_04

   我们目的是读取这两行数据,放到控制台来瞧瞧(其实也可以写到数据库或者另外一个excel文件中: 然后你会发现其实这就是 批量导入、导出的雏形


 

   上代码ExcelRead:

 

package com.poi.second;

import java.io.FileInputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
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.poifs.filesystem.POIFSFileSystem;

/**
 * 读excel
 * @author 钟林森
 *
 */
public class ExcelRead {
	public static void main(String[] args) throws Exception {

		//读取一个excel表的内容
		InputStream stream = new FileInputStream("E:\\java_BasicWeb\\someFiles\\excel读数据.xls");
		POIFSFileSystem fs = new POIFSFileSystem(stream);
		HSSFWorkbook wb = new HSSFWorkbook(fs);

		//获取excel表的第一个sheet
		HSSFSheet sheet = wb.getSheetAt(0);
		if (sheet == null) {
			return;
		}

		//遍历该sheet的行
		for (int rowNum = 0; rowNum <= sheet.getLastRowNum(); rowNum++) {
			HSSFRow row = sheet.getRow(rowNum);
			if (row == null) {
				continue;
			}

			//再遍历改行的所有列
			for(int cellNum = 0; cellNum <= row.getLastCellNum(); cellNum++) {
				HSSFCell cell = row.getCell(cellNum);
				if (cell == null) {
					continue;
				}
				
				
				String strVal=readCellSecondMethod(cell);
				if (cellNum==2) {
					strVal=strVal.contains(".")?strVal.substring(0, strVal.indexOf(".")):strVal;
				}
				System.out.print(" " + strVal);
				
				//System.out.print(" " + readCellFirstMethod(cell));
				//System.out.print(" " + readCellSecondMethod(cell));
				
			}
			System.out.println();
		}

		stream.close();
	}

	/**第一种方法
	 * 读取excel单元格的内容并针对其type进行不同的处理,
	 * 其中就包含  读取excel表格中日期格式的cell
	 * @param cell
	 * @return
	 */
	public static String readCellFirstMethod(HSSFCell cell) {
		if (cell.getCellType() == HSSFCell.CELL_TYPE_BOOLEAN) {
			return String.valueOf(cell.getBooleanCellValue());
		} else if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
			if (HSSFDateUtil.isCellDateFormatted(cell)) {
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				return sdf.format(HSSFDateUtil.getJavaDate(cell.getNumericCellValue())).toString();
			}
			return String.valueOf(cell.getNumericCellValue());
		} else {
			return cell.getStringCellValue();
		}
	}

	/**第二种方法
	 * 读取excel单元格的内容并针对其type进行不同的处理,
	 * 其中就包含  读取excel表格中日期格式的cell
	 * @param cell
	 * @return
	 */
	public static String readCellSecondMethod(HSSFCell cell) {
		//DecimalFormat df = new DecimalFormat("#");
		if (cell == null) {
			return "";
		}
		switch (cell.getCellType()) {
		
			//数字
			case HSSFCell.CELL_TYPE_NUMERIC:
				
				//日期格式的处理
				if (HSSFDateUtil.isCellDateFormatted(cell)) {
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
					return sdf.format(HSSFDateUtil.getJavaDate(cell.getNumericCellValue())).toString();
				}
				
				return String.valueOf(cell.getNumericCellValue());
				//return df.format(cell.getNumericCellValue());
				
			//字符串
			case HSSFCell.CELL_TYPE_STRING:
				return cell.getStringCellValue();
			
			//公式
			case HSSFCell.CELL_TYPE_FORMULA:
				return cell.getCellFormula();
				
			//空白
			case HSSFCell.CELL_TYPE_BLANK:
				return "";
			
			//布尔取值
			case HSSFCell.CELL_TYPE_BOOLEAN:
				return cell.getBooleanCellValue() + "";
			
			//错误类型
			case HSSFCell.CELL_TYPE_ERROR:
				return cell.getErrorCellValue() + "";
		}
		
		return "";
	}

}

 

 

 

    看控制台:

JAVA POI设置单元格居中 java poi操作excel_JAVA POI设置单元格居中_05