java poi操作excel示例代码
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示例代码的更多相关文章
- java POI创建Excel示例(xslx和xsl区别 )
Java用来处理office类库有很多,其中POI就是比较出名的一个,它是apache的类库,现在版本到了3.10,也就是2014年2月8号这个版本. 在处理PPT,Excel和Word前,需要导入以 ...
- java poi操作excel 添加 锁定单元格保护
Excel的book保护是很常用的,主要是不想让别人修改Excel的时候用.这样能够避免恶意随便修改数据,提高数据的可信度. 下面介绍JAVA POI来实现设置book保护: 使用HSSFSheet类 ...
- Java POI 操作Excel(读取/写入)
pom.xml依赖: <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi< ...
- java poi 操作
Java POI 操作Excel(读取/写入) https://www.cnblogs.com/dzpykj/p/8417738.html Java操作Excel之Poi基本操作 https://my ...
- 在java poi导入Excel通用工具类示例详解
转: 在java poi导入Excel通用工具类示例详解 更新时间:2017年09月10日 14:21:36 作者:daochuwenziyao 我要评论 这篇文章主要给大家介绍了关于在j ...
- java使用POI操作excel文件,实现批量导出,和导入
一.POI的定义 JAVA中操作Excel的有两种比较主流的工具包: JXL 和 POI .jxl 只能操作Excel 95, 97, 2000也即以.xls为后缀的excel.而poi可以操作Exc ...
- JAVA的POI操作Excel
1.1Excel简介 一个excel文件就是一个工作簿workbook,一个工作簿中可以创建多张工作表sheet,而一个工作表中包含多个单元格Cell,这些单元格都是由列(Column)行(Row)组 ...
- java 使用jxl poi 操作excel
java操作excel 创建.修改 xls 文件 JAVA操作Excel文件 Java生成和操作Excel文件 java导出Excel通用方法 Java 实现导出excel表 POI Java PO ...
- java里poi操作excel的工具类(兼容各版本)
转: java里poi操作excel的工具类(兼容各版本) 下面是文件内具体内容,文件下载: import java.io.FileNotFoundException; import java.io. ...
随机推荐
- WebSocket handshake: Unexpected response code: 404
在执行 http://www.cnblogs.com/best/p/5695570.html 提供的 websocket时候, 报错了 “WebSocket handshake: Unexpe ...
- vue中使用滚动效果
new Vue({ el: '#app', data: function data() { return { bottom: false, beers: [] }; }, watch: { botto ...
- sql中--行处理数据的两种方式
--创建待使用的表格CREATE TABLE Orders ( OrderID INT , CostValue DECIMAL(18, 2) );WITH cte_temp AS ( SELECT 1 ...
- Benelux Algorithm Programming Contest 2014 Final(第二场)
B:Button Bashing You recently acquired a new microwave, and noticed that it provides a large number ...
- Audio / Video Playback
For Developers > Design Documents > Audio / Video Playback Interested in helping out? Ch ...
- AtCoderBeginner091-C 2D Plane 2N Points 模拟问题
题目链接:https://abc091.contest.atcoder.jp/tasks/arc092_a 题意 On a two-dimensional plane, there are N red ...
- 新机器的vim配置
最近一直用vim去写acm代码,算是一种练习吧. 用着用着感觉不错,最近也稍微配置了一下vim,用着更舒服了 键盘映射 ESC<->CapsLock 我们知道vim有自带的键盘映射命令,但 ...
- SweetAlert的入门
在做后台管理系统,在用户交互这块(弹窗.提示相关),用了一款还不错的插件SweetAlert(一款原生js提示框,允许自定义,支持设置提示框标题.提示类型.确认取消按钮文本.点击后回调函数等等), 效 ...
- Python中的引用计数法
目录 引用计数法 增量操作 计数器溢出的问题 减量操作 终结器 插入计数处理 引用计数法 增量操作 如果对象的引用数量增加,就在该对象的计数器上进行增量操作.在实际中它是由宏Py_INCREF() 执 ...
- CMSIS-RTOS功能概述
以下列表简要概述了所有CMSIS-RTOS功能.标有$的函数是可选的.特定的CMSIS-RTOS实现可能无法提供所有功能,但osFeatureXXXX定义明确指出了这一点. 注意 RTX实现不支持的功 ...