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. ...
随机推荐
- 将double数据保留两位小数
private double formatDouble(double number) { DecimalFormat df = new DecimalFormat("#.00"); ...
- HTML5的核心内容
开发者可以放心地使用html5的理由 兼容性.HTML5在老版本的浏览器可以正常运行,同时支持HTML5的新浏览器也能正常运行HTML4,用HTML4创建出来的网站不是必须全部重建的. 实用性.HTM ...
- 记intel杯比赛中各种bug与debug【其五】:朴素贝叶斯分类器的实现和针对性的优化
咱这个项目最主要的就是这个了 贝叶斯分类器用于做可以统计概率的二元分类 典型的例子就是垃圾邮件过滤 理论基础 对于贝叶斯算法,这里附上两个链接,便于理解: 朴素贝叶斯分类器的应用-阮一峰的网络日志 基 ...
- windows用xstart远程连接linux图形用户界面
转载:https://blog.csdn.net/yabingshi_tech/article/details/51839379 双击xstart 输入:/usr/bin/xterm -ls -dis ...
- Linux Shell脚本编程-基础2
命令退出状态码 bash每个命令,执行状态都有返回值 0表示成功 非0表示失败(1-255) $?特殊变量可以打印出上一条命令的状态返回值 脚本的状态返回值是脚本执行的最后一条命令 自定义脚本状态返 ...
- screen---管理会话
Screen是一款由GNU计划开发的用于命令行终端切换的自由软件.用户可以通过该软件同时连接多个本地或远程的命令行会话,并在其间自由切换.GNU Screen可以看作是窗口管理器的命令行界面版本.它提 ...
- python 调试大法-大笨蛋的笔记
说在前面 我觉得没有什么错误是调试器无法解决的,如果没有,那我再说一遍,如果有,那当我没说 一.抛出异常 可以通过 raise 语句抛出异常,使程序在我们已经知道的缺陷处停下,并进入到 except ...
- Python组织文件 实践:将文件的不同版本备份为ZIP文件
功能:备份文件夹.能将文件的不同版本备份下来,并且每个有不同的名字 #! python3 # backupToZip.py - 备份文件的不同版本到压缩文件中 import zipfile,os #f ...
- 题解 P3243 【[HNOI2015]菜肴制作】
这道题看起来就是个裸的拓扑排序,抄上模板就能AC. 上面这种想法一看就不现实,然鹅我第一次还真就这么写了,然后被随意hack. 我们需要注意一句话: 现在,酒店希望能求出一个最优的菜肴的制作顺序,使得 ...
- 题解 P3605 【[USACO17JAN]Promotion Counting晋升者计数】
这道题开10倍左右一直MLE+RE,然后尝试着开了20倍就A了...窒息 对于这道题目,我们考虑使用线段树合并来做. 所谓线段树合并,就是把结构相同的线段树上的节点的信息合在一起,合并的方式比较类似左 ...