java使用poi包将数据写入Excel表格
1、Excel相关操作代码
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List; 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.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.springframework.stereotype.Component; /**
* @Description:
* @author * @date 创建时间:2016年12月8日下午2:38:47
* @version 1.0
*/
@Component
public class ExcelManage {
private HSSFWorkbook workbook = null; /**
* 判断文件是否存在
* @param filePath 文件路径
* @return
*/
public boolean fileExist(String filePath){
boolean flag = false;
File file = new File(filePath);
flag = file.exists();
return flag;
} /**
* 判断文件的sheet是否存在
* @param filePath 文件路径
* @param sheetName 表格索引名
* @return
*/
public boolean sheetExist(String filePath,String sheetName){
boolean flag = false;
File file = new File(filePath);
if(file.exists()){ //文件存在
//创建workbook
try {
workbook = new HSSFWorkbook(new FileInputStream(file));
//添加Worksheet(不添加sheet时生成的xls文件打开时会报错)
HSSFSheet sheet = workbook.getSheet(sheetName);
if(sheet!=null)
flag = true;
} catch (Exception e) {
e.printStackTrace();
}
}else{ //文件不存在
flag = false;
}
return flag;
}
/**
* 创建新Sheet并写入第一行数据
* @param filePath excel的路径
* @param sheetName 要创建的表格索引
* @param titleRow excel的第一行即表格头
* @throws IOException
* @throws FileNotFoundException
*/
public void createSheet(String filePath,String sheetName,String titleRow[]) throws FileNotFoundException, IOException{
FileOutputStream out = null;
File excel = new File(filePath); // 读取文件
FileInputStream in = new FileInputStream(excel); // 转换为流
workbook = new HSSFWorkbook(in); // 加载excel的 工作目录 workbook.createSheet(sheetName); // 添加一个新的sheet
//添加表头
Row row = workbook.getSheet(sheetName).createRow(0); //创建第一行
try {
for(int i = 0;i < titleRow.length;i++){
Cell cell = row.createCell(i);
cell.setCellValue(titleRow[i]);
}
out = new FileOutputStream(filePath);
workbook.write(out);
}catch (Exception e) {
e.printStackTrace();
}finally {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
99 /**
* 创建新excel.
* @param filePath excel的路径
* @param sheetName 要创建的表格索引
* @param titleRow excel的第一行即表格头
*/
public void createExcel(String filePath,String sheetName,String titleRow[]){
//创建workbook
workbook = new HSSFWorkbook();
//添加Worksheet(不添加sheet时生成的xls文件打开时会报错)
workbook.createSheet(sheetName);
//新建文件
FileOutputStream out = null;
try {
//添加表头
Row row = workbook.getSheet(sheetName).createRow(0); //创建第一行
for(int i = 0;i < titleRow.length;i++){
Cell cell = row.createCell(i);
cell.setCellValue(titleRow[i]);
}
out = new FileOutputStream(filePath);
workbook.write(out);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 删除文件.
* @param filePath 文件路径
*/
public boolean deleteExcel(String filePath){
boolean flag = false;
File file = new File(filePath);
// 判断目录或文件是否存在
if (!file.exists()) {
return flag;
} else {
// 判断是否为文件
if (file.isFile()) { // 为文件时调用删除文件方法
file.delete();
flag = true;
}
}
return flag;
}
/**
* 往excel中写入.
* @param filePath 文件路径
* @param sheetName 表格索引
* @param object
*/
public void writeToExcel(String filePath,String sheetName, Object object,String titleRow[]){
//创建workbook
File file = new File(filePath);
try {
workbook = new HSSFWorkbook(new FileInputStream(file));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
FileOutputStream out = null;
HSSFSheet sheet = workbook.getSheet(sheetName);
// 获取表格的总行数
int rowCount = sheet.getLastRowNum() + 1; // 需要加一
try {
Row row = sheet.createRow(rowCount); //最新要添加的一行
//通过反射获得object的字段,对应表头插入
// 获取该对象的class对象
Class<? extends Object> class_ = object.getClass(); for(int i = 0;i < titleRow.length;i++){
String title = titleRow[i];
String UTitle = Character.toUpperCase(title.charAt(0))+ title.substring(1, title.length()); // 使其首字母大写;
String methodName = "get"+UTitle;
Method method = class_.getDeclaredMethod(methodName); // 设置要执行的方法
String data = method.invoke(object).toString(); // 执行该get方法,即要插入的数据
Cell cell = row.createCell(i);
cell.setCellValue(data);
}
out = new FileOutputStream(filePath);
workbook.write(out);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
2、main方法调用方式
public static void main(String[] args) {
String filePath = "result/数据汇总.xls";
String sheetName = "测试";
//Excel文件易车sheet页的第一行
String title[] = {"日期", "城市","新发布车源数"};
//Excel文件易车每一列对应的数据
String titleDate[] = {"date", "city","newPublish"};
ExcelManage em = new ExcelManage();
//判断该名称的文件是否存在
boolean fileFlag = em.fileExist(filePath);
if(!fileFlag){
em.createExcel(filePath,sheetName,title);
}
//判断该名称的Sheet是否存在
boolean sheetFlag = em.sheetExist(filePath,sheetName);
//如果该名称的Sheet不存在,则新建一个新的Sheet
if(!sheetFlag){
try {
em.createSheet(filePath,sheetName,title);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
YiCheData user = new YiCheData();
user.setDate("206-12-21");
user.setCity("北京");
user.setNewPublish("5");
//写入到excel
em.writeToExcel(filePath,sheetName,user,titleDate);
}
3、用于测试的bean类
public class YiCheData {
private String date;
private String city;
private String newPublish;
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getNewPublish() {
eturn newPublish;
}
public void setNewPublish(String newPublish) {
this.newPublish = newPublish;
}
}
以上代码请参考:http://www.open-open.com/lib/view/open1433238476150.html
java使用poi包将数据写入Excel表格的更多相关文章
- Java操作Jxl实现导出数据生成Excel表格数据文件
实现:前台用的框架是Easyui+Bootstrap结合使用,需要引入相应的Js.Css文件.页面:Jsp.拦截请求:Servlet.逻辑处理:ClassBean.数据库:SQLserver. 注意: ...
- 《程序实现》从xml、txt文件里读取数据写入excel表格
直接上码 import java.io.BufferedReader; import java.io.DataInputStream; import java.io.File; import java ...
- python数据写入Excel表格
from openpyxl import Workbook def main(): sheet_name = "表名1" row_count = 6 # 行数 info_resul ...
- java使用POI解析2007以上的Excel表格
来自http://hao0610.iteye.com/blog/1160678 使用poi来解析Excel的xls和xlsx. 解析xls: package xls; import java.io.F ...
- JXL读取写入excel表格数据
问题描述: 使用java的jxl包创建.写入excel表格数据 问题解决: (1)说明 (2)写入execel数据 注: 以上是写入数据需要调用的函数接口 注: 具体接口调用过程,如上所示 (3)读取 ...
- java数据写入Excel
正好最近公司要写一个对账的功能,后台用java从银行获得对账信息,数据是json类型的,然后写入excel中发送给一卡通中心的服务器上,网上找了很多代码,然后整合和改正,代码如下. import ja ...
- JAVA读取、写入Excel表格(含03版)
引言 工作中可能会遇到对Excel读取和写入,如果我们自己手动写的话,会很麻烦,但是Apache中有poi工具类.poi工具类封装好了对于Excel读取和写入,我们需要用的时候,直接调用该方法就好了. ...
- java的poi技术读,写Excel[2003-2007,2010]
在上一篇blog:java的poi技术读取Excel[2003-2007,2010] 中介绍了关于java中的poi技术读取excel的相关操作 读取excel和MySQL相关: java的poi技术 ...
- 将Oracle数据库中的数据写入Excel
将Oracle数据库中的数据写入Excel 1.准备工作 Oracle数据库"TBYZB_FIELD_PRESSURE"表中数据如图: Excel模板(201512.xls): 2 ...
随机推荐
- 【Python基础学习四】字符串(string)
Python 字符串 字符串是 Python 中最常用的数据类型.可以使用引号('或")来创建字符串. 创建字符串很简单,只要为变量分配一个值即可.例如: var1 = 'hello' va ...
- 2016年11月28日--ADO.Net 查、插、删、改 小练习
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.T ...
- python3简单爬虫
最近在抽空学了一下python,于量就拿爬是练了下手,不得不说python的上手非常简单.在网上找了一下,大都是python2的帖子,于是随手写了个python3的.代码非常简单就不解释了,直接贴代码 ...
- python的一道面试题 __call__ 的使用.
class Person: def __init__(self): self.age = 1 def __call__(self, *args, **kwargs): print 'age', sel ...
- python在windows下获取cpu、硬盘、bios、主板序列号
测试 此处使用的是wmi库,可以去google里面搜索“python wmi” import os, sysimport timeimport wmi,zlib def get_cpu_info() ...
- 3.EasyUI学习总结(三)——easyloader源码分析
easyloader模块是用来加载jquery easyui的js和css文件的,即easyloader可以在调用的时候自动加载当前页面所需的文件,不用再自己引用, 而且它可以分析模块的依赖关系,先加 ...
- .NET LINQ 投影运算
投影运算 投影是指将对象转换为一种新形式的操作,该形式通常只包含那些将随后使用的属性. 通过使用投影,您可以构建依据每个对象生成的新类型. 您可以映射属性,并对该属性执行数学函数. 还可以在 ...
- node07-http
目录:node01-创建服务器 node02-util node03-events node04-buffer node05-fs node06-path node07-http node08-exp ...
- 【XLL 框架库函数】 TempActiveRow/TempActiveRow12
创建一个包含所有激活工作表行的 XLOPER/XLOPER12 LPXLOPER TempActiveRow(WORD row); LPXLOPER12 TempActiveRow12(ROW row ...
- 【Xcode 4 无法打开 Xcode 5 DP 打开过的工程文件 解决方法】
试用Xcode 5 DP打开现有工程文件后再用Xcode4打开后 Xcode 4 会进入崩溃模式折腾了几次发现下面的方法可以让工程文件恢复 如果在Xcode5-DP中打开过xib文件需要在侧栏中修改I ...