import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Properties; import org.apache.poi.hssf.usermodel.HSSFCell;
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.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; public class ReadWriteExcelFile {
private static Properties props = new Properties();
static {
try {
InputStream is = ReadWriteExcelFile.class.getClassLoader().getResourceAsStream("META-INF/ExcelHeader.properties");
props.load(is);
} catch (Exception e) {
e.printStackTrace();
}
}
public static String getValue(String key) {
String value = "";
if (props.containsKey(key)) {
value = props.getProperty(key, "");
}
return value;
}
private final static Logger logger = LoggerFactory.getLogger(ReadWriteExcelFile.class);
@SuppressWarnings({ "resource", "rawtypes" })
public static void readXLSFile() throws IOException
{
InputStream ExcelFileToRead = new FileInputStream("E:/source/Test.xls");
HSSFWorkbook wb = new HSSFWorkbook(ExcelFileToRead); HSSFSheet sheet=wb.getSheetAt(0);
HSSFRow row;
HSSFCell cell; Iterator rows = sheet.rowIterator(); while (rows.hasNext())
{
row=(HSSFRow) rows.next();
Iterator cells = row.cellIterator(); while (cells.hasNext())
{
cell=(HSSFCell) cells.next(); if (cell.getCellType() == HSSFCell.CELL_TYPE_STRING)
{
System.out.print(cell.getStringCellValue()+" ");
}
else if(cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC)
{
System.out.print(cell.getNumericCellValue()+" ");
}
else
{
//U Can Handel Boolean, Formula, Errors
}
}
System.out.println();
} }
public static void writeXLSFile(List<? extends Recording> records) throws IOException{
//String directory=getValue("excel.file.directory");
String directory="E:/source";
Date d = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String date = sdf.format(d);
Recording record=records.get(0);
Class<? extends Recording> cls=record.getClass();
String className=cls.getCanonicalName();
String[] nameAlias=className.split("\\.");
String excelFileName=directory+File.separator+nameAlias[nameAlias.length-1]+date+".xls";
writeXLSFile(records,excelFileName);
} @SuppressWarnings("resource")
public static void writeXLSFile(List<? extends Recording> records,String excelFileName) throws IOException{ //String excelFileName = "E:/source/Test.xls";
String sheetName = "Sheet1";//name of sheet HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet(sheetName) ;
Recording record;
//excel header
HSSFRow row = sheet.createRow(0);
record=records.get(0);
Class<? extends Recording> cls=record.getClass();
String className=cls.getCanonicalName();
String[] nameAlias=className.split("\\.");
Field[] fields=cls.getDeclaredFields();
//去除serialVersionUID列,
List<Field> fieldsNoSer=new ArrayList<Field>();
for(int i=0;i<fields.length;i++){
String fieldName=fields[i].getName();
if(fieldName.equalsIgnoreCase("serialVersionUID")){
continue;
}else{
fieldsNoSer.add(fields[i]);
}
}
for(int i=0;i<fieldsNoSer.size();i++){
HSSFCell cell = row.createCell(i);
String fieldName=fieldsNoSer.get(i).getName();
cell.setCellValue(getValue(nameAlias[nameAlias.length-1]+"."+fieldName));
} //iterating r number of rows
for (int r=0;r < records.size(); r++ )
{
row = sheet.createRow(r+1);
record=records.get(r);
//table content
for (int c=0;c < fieldsNoSer.size(); c++ )
{
HSSFCell cell = row.createCell(c);
//加header,方法总变量的首字母大写
String fieldName=fieldsNoSer.get(c).getName();
try {
Method method=cls.getDeclaredMethod("get"+fieldName.substring(0,1).toUpperCase()+fieldName.substring(1));
Object ret=method.invoke(record);
if(null!=ret){
cell.setCellValue(method.invoke(record).toString());
} } catch (Exception e) {
logger.info("write xls error,please check it");
}
}
}
FileOutputStream fileOut = new FileOutputStream(excelFileName); //write this workbook to an Outputstream.
wb.write(fileOut);
fileOut.flush();
fileOut.close();
} @SuppressWarnings({ "resource", "unused", "rawtypes" })
public static void readXLSXFile() throws IOException
{
InputStream ExcelFileToRead = new FileInputStream("E:/source/Test1.xlsx");
XSSFWorkbook wb = new XSSFWorkbook(ExcelFileToRead); XSSFWorkbook test = new XSSFWorkbook(); XSSFSheet sheet = wb.getSheetAt(0);
XSSFRow row;
XSSFCell cell; Iterator rows = sheet.rowIterator(); while (rows.hasNext())
{
row=(XSSFRow) rows.next();
Iterator cells = row.cellIterator();
while (cells.hasNext())
{
cell=(XSSFCell) cells.next(); if (cell.getCellType() == XSSFCell.CELL_TYPE_STRING)
{
System.out.print(cell.getStringCellValue()+" ");
}
else if(cell.getCellType() == XSSFCell.CELL_TYPE_NUMERIC)
{
System.out.print(cell.getNumericCellValue()+" ");
}
else
{
//U Can Handel Boolean, Formula, Errors
}
}
System.out.println();
} } @SuppressWarnings("resource")
public static void writeXLSXFile() throws IOException { String excelFileName = "E:/source/Test1.xlsx";//name of excel file String sheetName = "Sheet1";//name of sheet XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = wb.createSheet(sheetName) ; //iterating r number of rows
for (int r=0;r < 5; r++ )
{
XSSFRow row = sheet.createRow(r); //iterating c number of columns
for (int c=0;c < 5; c++ )
{
XSSFCell cell = row.createCell(c); cell.setCellValue("Cell "+r+" "+c);
}
} FileOutputStream fileOut = new FileOutputStream(excelFileName); //write this workbook to an Outputstream.
wb.write(fileOut);
fileOut.flush();
fileOut.close();
} public static void main(String[] args) throws IOException, NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
List<Log> logs=new ArrayList<Log>();
for(int i=1;i<2;i++){
Log log=new Log();
log.setId(Long.parseLong(""+(i+6)));
log.setUserId(Long.parseLong(""+i));
log.setUserName("www"+i);
logs.add(log);
}
writeXLSFile(logs,"E:/source/aa.xls"); }

java poi操作excel示例代码的更多相关文章

  1. java POI创建Excel示例(xslx和xsl区别 )

    Java用来处理office类库有很多,其中POI就是比较出名的一个,它是apache的类库,现在版本到了3.10,也就是2014年2月8号这个版本. 在处理PPT,Excel和Word前,需要导入以 ...

  2. java poi操作excel 添加 锁定单元格保护

    Excel的book保护是很常用的,主要是不想让别人修改Excel的时候用.这样能够避免恶意随便修改数据,提高数据的可信度. 下面介绍JAVA POI来实现设置book保护: 使用HSSFSheet类 ...

  3. Java POI 操作Excel(读取/写入)

    pom.xml依赖: <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi< ...

  4. java poi 操作

    Java POI 操作Excel(读取/写入) https://www.cnblogs.com/dzpykj/p/8417738.html Java操作Excel之Poi基本操作 https://my ...

  5. 在java poi导入Excel通用工具类示例详解

    转: 在java poi导入Excel通用工具类示例详解 更新时间:2017年09月10日 14:21:36   作者:daochuwenziyao   我要评论   这篇文章主要给大家介绍了关于在j ...

  6. java使用POI操作excel文件,实现批量导出,和导入

    一.POI的定义 JAVA中操作Excel的有两种比较主流的工具包: JXL 和 POI .jxl 只能操作Excel 95, 97, 2000也即以.xls为后缀的excel.而poi可以操作Exc ...

  7. JAVA的POI操作Excel

    1.1Excel简介 一个excel文件就是一个工作簿workbook,一个工作簿中可以创建多张工作表sheet,而一个工作表中包含多个单元格Cell,这些单元格都是由列(Column)行(Row)组 ...

  8. java 使用jxl poi 操作excel

    java操作excel  创建.修改 xls 文件 JAVA操作Excel文件 Java生成和操作Excel文件 java导出Excel通用方法 Java 实现导出excel表 POI Java PO ...

  9. java里poi操作excel的工具类(兼容各版本)

    转: java里poi操作excel的工具类(兼容各版本) 下面是文件内具体内容,文件下载: import java.io.FileNotFoundException; import java.io. ...

随机推荐

  1. <Sicily>Inversion Number(线段树求逆序数)

    一.题目描述 There is a permutation P with n integers from 1 to n. You have to calculate its inversion num ...

  2. 2018年湘潭大学程序设计竞赛 Fibonacci进制

    Fibonacci数是非常有名的一个数列,它的公式为 f(n)=f(n-1)+f(n-2),f(0)=1,f(1)=2.  我们可以把任意一个数x表示成若干不相同的Fibonacci数的和, 比如说1 ...

  3. WIFI 概览

      概览 Android 提供默认 Android 框架实现,其中包括对各种 WLAN 协议和模式的支持,这些协议和模式包括: WLAN 基础架构 (STA) 网络共享模式或仅限本地模式下的 WLAN ...

  4. caffe(2) 数据层及参数

    要运行caffe,需要先创建一个模型(model),如比较常用的Lenet,Alex等, 而一个模型由多个屋(layer)构成,每一屋又由许多参数组成.所有的参数都定义在caffe.proto这个文件 ...

  5. 在 yii2.0 框架中封装导出html 表格样式 Excel 类

    在 vendor/yiisoft/yii2/helpers/ 创建一个 Excel.php <?php namespace yii\helpers;   class Excel{         ...

  6. 记intel杯比赛中各种bug与debug【其二】:intel caffe的使用和大坑

    放弃使用pytorch,学习caffe 本文仅记录个人观点,不免存在许多错误 Caffe 学习 caffe模型生成需要如下步骤 编写network.prototxt 编写solver.prototxt ...

  7. Centos7(阿里云服务器)安装Anaconda的详细步骤与心得

    在本地安装Anaconda的各个版本的文章已经很多,但是感觉不是很详细,因此,在此发发自己在Centos7(阿里云服务器)安装Anaconda的心得和步骤: 注:需要注意的地方会用不同颜色区别. 1. ...

  8. 紫书 习题 10-2 UVa 808(建立坐标+找规律)

    这次是我遇见过最迷的一次 我写的程序uDebug全过 和ac程序对拍也过,求出来的坐标是一模一样的,最后结果输出的方式也是一样的 交上去就是错的 迷 第一次遇到这种情况 大佬在哪里 #include& ...

  9. Spring学习总结(12)——Druid连接池及监控在spring配置

    Druid连接池及监控在spring配置如下: <bean id="dataSource" class="com.alibaba.druid.pool.DruidD ...

  10. cxf 实例解读

    1.sample 实例之一---java_first_pojo 服务端发布服务的方法: 1 HelloWorldImpl helloworldImpl = new HelloWorldImpl(); ...