Java操作excel-兼容office 2007版本之后

 

前言

office2007版本有一次标准升级,最为明显的就是excel文件的文件名后缀(文件扩展名)由xls变成了xlsx,这是需要注意的地方,因为按照xls格式来处理xlsx格式的文件是无法操作的,

反过来,使用操作xlsx格式的文件的方式操作文件扩展名(文件位缀)为xls是没有问题的。

因为本质上来说,office之后的版本对之前的版本是兼容的,这个在Office 开发组件poi中也得到了提现。即向下兼容,或者向后兼容的,只旧系统的东西依旧可以在新系统被正常使用。

 

需要注意的是,本文有使用log4j2,如果你的环境没有配置日志,可以把日志代码去除,换为System.out,println();

如果你对log4j2感兴趣,可以参考APACHE LOG4J™ 2 学习笔记-log4j2 环境部署到各种类型输出+maven\mysql\滚动文件\控制台\异步\过滤器

 

maven 依赖

 


		
			org.apache.poi
			poi
			3.14
		

		
			org.apache.poi
			poi-ooxml
			3.14
		
		
			org.apache.poi
			poi-ooxml-schemas
			3.14
		
		
			org.apache.xmlbeans
			xmlbeans
			2.6.0
		

 

 

 

 

 

 

poi是专门操作office文件的免费的API:http://poi.apache.org/

 

废话不多说了,直接贴代码:

 

·读取excel文件   readOfficeExcelFile

·在原先的excel文件续写-没有加末尾判断,可能会造成数据被覆盖  writeOfficeExcelFile

·程序新建一个excle文件,并且填充一些数据  createOfficeExcelFile

 

枚举类提供常量-本例中仅部分有用到

 

package com.bestcxx.mavenstu.mavenssh.util;

/**
 * @theme 枚举类-设置静态变量
 * @author wujie
 */
public enum EnumUtil {
	//可以以逗号间隔 
	FILE_OFFICE_EXCEL_NAME("officeExcelDemo.xlsx"),
	FILE_OFFICE_EXCEL_PATH("src/main/webapp/WEB-INF/file"),//office 的 excel文件
	COMMON_DATABASE_PROPERTIES("config/jdbc.properties"),
	COMMON_ENCODING("utf-8"),
	FILE_TXT_PATH("src/main/webapp/WEB-INF/file/filetxt.txt"),//src/main/resources/file/filetxt.txt 也是可以的,都是相对路径
	WECHAT_APPID("appid"),				   	//微信公众号平台账户的appid
	WECHAT_APPSECRET("appsecret"), //微信公众号平台账户的appsecret
	PROXY_SERVICEPORT_SHEZHI("0"),     //代理设置-是否启用代理,0-NO,1-YES
	PROXY_PROXYHOST("192.168.1.1"),    //代理设置-代理IP
	PROXY_PROXYPORT("8080");    	  //代理设置-代理端口
	
      
    private String temStr;  
    private EnumUtil(String temStr){  
        this.temStr=temStr;  
    }  
    @Override  
    public String toString() {
        return String.valueOf (this.temStr);  
    }  
}

 

 

 

 

 

 

工具类

 

package com.bestcxx.mavenstu.mavenssh.file;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
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.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

/**
 * 
 * @theme 操作 excel 文件的工具类
 * @author wujie
 * @Datetime 2017年3月24日 下午2:52:10
 * HSSF - 提供读写Microsoft Excel格式档案的功能。 
 * XSSF - 提供读写Microsoft Excel OOXML格式档案的功能。 
 * HWPF - 提供读写Microsoft Word格式档案的功能。 
 * HSLF - 提供读写Microsoft PowerPoint格式档案的功能。 
 * HDGF - 提供读写Microsoft Visio格式档案的功能。 
 */
public class FileOfficeExcel {
	private static Logger logger=LogManager.getLogger(FileOfficeExcel.class);
	
	/**
	 * 
	 * @instruction 读取excel文件
	 * @Datetime 2017年3月27日 下午3:59:15
	 * @param excelPath 文件夹路径
	 * @param excelName 文件名字  officeExcelDemo.xlsx 
	 */
	public void readOfficeExcelFile(String excelPath,String excelName) {
		try {
			
			File file = new File(excelPath, excelName);

			// 文件转化为输入流
			FileInputStream fi;

			fi = new FileInputStream(file);

			// 操作excel文件需要创建Workbook 对象
			Workbook wb;
			wb = WorkbookFactory.create(fi);

			// 获得具体的一个sheet页-这里是第一个 
			Sheet sheet = wb.getSheetAt(0);

			// 获取最后一行的行号
			int rowNum = sheet.getLastRowNum() + 1;//这里加1,是因为获取的是序数值,而函数是从0开始计数的
			//logger.info("\n获取第一个 sheet 包含行数为:"+rowNum);
			
			// 获取某一行的数据-这里是第i行
			for(int i=2;i

 

 

 

 

 

测试类

 

package com.bestcxx.mavenstu.mavenssh.file;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.junit.Ignore;
import org.junit.Test;

import com.bestcxx.mavenstu.mavenssh.util.EnumUtil;

public class FileOfficeExcelTest {
	private static Logger logger=LogManager.getLogger(FileOfficeExcelTest.class);
	
	@Test
	//@Ignore
	public void testReadOfficeExcelFile(){
		FileOfficeExcel f=new FileOfficeExcel();
		//excel 所在文件夹
		String excelPath = EnumUtil.FILE_OFFICE_EXCEL_PATH.toString();
		
		//excel 名称
		String excelName = EnumUtil.FILE_OFFICE_EXCEL_NAME.toString();
		
		f.readOfficeExcelFile(excelPath,excelName);
	}
	
	@Test
	public void testWriteOfficeExcelFile(){
		FileOfficeExcel f=new FileOfficeExcel();
		
		//excel 所在文件夹
		String excelPath = EnumUtil.FILE_OFFICE_EXCEL_PATH.toString();
		//excel 名称
		String excelName = "test.xlsx";
		
		f.writeOfficeExcelFile(excelPath,excelName);
	}
	
	@Test
	public void testCreateOfficeExcelFile(){
		FileOfficeExcel f=new FileOfficeExcel();
		
		//excel 所在文件夹
		String excelPath = EnumUtil.FILE_OFFICE_EXCEL_PATH.toString();
		//excel 名称
		String excelName = "test.xlsx";
		
		f.createOfficeExcelFile(excelPath,excelName);
	}

}

 

 

 

 

 

本文属于作者原创,转载请声明:http://blog.csdn.net/bestcxx

+20170811 补充+如果生成的文件供下载,fileName为 name.xls或者 name.xlsx格式

 

OutputStream out = null;
		try {
			response.setContentType("application/vnd.ms-excel");   
			response.setHeader("Content-disposition", "attachment;filename=" + fileName);  
			out = response.getOutputStream();
			wb.write(out);//Workbook wb = new HSSFWorkbook();
			out.flush();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				if (wb != null) {wb.close();}
				if (out != null) {out.close();}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

+20180710 补充+文件字段分为 文本,数字,日期三种类型,而且有可能为空

if(null!=row.getCell(1)){//普通文本
           row.getCell(1).getStringCellValue();
        }

        if(null!=row.getCell(2)){//整形数字
            //这里涉及到一个类型转化,Excel 数字,但是只能先以 dubbo 类型来处理,转化为整形
            (int)row.getCell(2).getNumericCellValue();
        }

        if(null!=row.getCell(7)){//小数类型
            e.setBusinessInsuranceAmount(new BigDecimal(row.getCell(7).getNumericCellValue()));
        }

if(null!=row.getCell(3)){//日期类型
            //该类型为日期类型
            row.getCell(3).getDateCellValue();
        }

 

 

 

 

 

 

 

 

 

 

 

你可能感兴趣的:(积累)