1. import java.io.File;
  2. import java.io.FileInputStream;
  3. import java.io.FileOutputStream;
  4. import java.io.IOException;
  5. import java.io.InputStream;
  6. import java.text.SimpleDateFormat;
  7. import java.util.ArrayList;
  8. import java.util.Date;
  9. import java.util.Iterator;
  10. import java.util.List;
  11. import java.util.Properties;
  12.  
  13. import org.apache.poi.hssf.usermodel.HSSFCell;
  14. import org.apache.poi.hssf.usermodel.HSSFRow;
  15. import org.apache.poi.hssf.usermodel.HSSFSheet;
  16. import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  17. import org.apache.poi.xssf.usermodel.XSSFCell;
  18. import org.apache.poi.xssf.usermodel.XSSFRow;
  19. import org.apache.poi.xssf.usermodel.XSSFSheet;
  20. import org.apache.poi.xssf.usermodel.XSSFWorkbook;
  21.  
  22. import java.lang.reflect.Field;
  23. import java.lang.reflect.InvocationTargetException;
  24. import java.lang.reflect.Method;
  25. import org.slf4j.Logger;
  26. import org.slf4j.LoggerFactory;
  27.  
  28. public class ReadWriteExcelFile {
  29. private static Properties props = new Properties();
  30. static {
  31. try {
  32. InputStream is = ReadWriteExcelFile.class.getClassLoader().getResourceAsStream("META-INF/ExcelHeader.properties");
  33. props.load(is);
  34. } catch (Exception e) {
  35. e.printStackTrace();
  36. }
  37. }
  38. public static String getValue(String key) {
  39. String value = "";
  40. if (props.containsKey(key)) {
  41. value = props.getProperty(key, "");
  42. }
  43. return value;
  44. }
  45. private final static Logger logger = LoggerFactory.getLogger(ReadWriteExcelFile.class);
  46. @SuppressWarnings({ "resource", "rawtypes" })
  47. public static void readXLSFile() throws IOException
  48. {
  49. InputStream ExcelFileToRead = new FileInputStream("E:/source/Test.xls");
  50. HSSFWorkbook wb = new HSSFWorkbook(ExcelFileToRead);
  51.  
  52. HSSFSheet sheet=wb.getSheetAt(0);
  53. HSSFRow row;
  54. HSSFCell cell;
  55.  
  56. Iterator rows = sheet.rowIterator();
  57.  
  58. while (rows.hasNext())
  59. {
  60. row=(HSSFRow) rows.next();
  61. Iterator cells = row.cellIterator();
  62.  
  63. while (cells.hasNext())
  64. {
  65. cell=(HSSFCell) cells.next();
  66.  
  67. if (cell.getCellType() == HSSFCell.CELL_TYPE_STRING)
  68. {
  69. System.out.print(cell.getStringCellValue()+" ");
  70. }
  71. else if(cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC)
  72. {
  73. System.out.print(cell.getNumericCellValue()+" ");
  74. }
  75. else
  76. {
  77. //U Can Handel Boolean, Formula, Errors
  78. }
  79. }
  80. System.out.println();
  81. }
  82.  
  83. }
  84. public static void writeXLSFile(List<? extends Recording> records) throws IOException{
  85. //String directory=getValue("excel.file.directory");
  86. String directory="E:/source";
  87. Date d = new Date();
  88. SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
  89. String date = sdf.format(d);
  90. Recording record=records.get(0);
  91. Class<? extends Recording> cls=record.getClass();
  92. String className=cls.getCanonicalName();
  93. String[] nameAlias=className.split("\\.");
  94. String excelFileName=directory+File.separator+nameAlias[nameAlias.length-1]+date+".xls";
  95. writeXLSFile(records,excelFileName);
  96. }
  97.  
  98. @SuppressWarnings("resource")
  99. public static void writeXLSFile(List<? extends Recording> records,String excelFileName) throws IOException{
  100.  
  101. //String excelFileName = "E:/source/Test.xls";
  102. String sheetName = "Sheet1";//name of sheet
  103.  
  104. HSSFWorkbook wb = new HSSFWorkbook();
  105. HSSFSheet sheet = wb.createSheet(sheetName) ;
  106. Recording record;
  107. //excel header
  108. HSSFRow row = sheet.createRow(0);
  109. record=records.get(0);
  110. Class<? extends Recording> cls=record.getClass();
  111. String className=cls.getCanonicalName();
  112. String[] nameAlias=className.split("\\.");
  113. Field[] fields=cls.getDeclaredFields();
  114. //去除serialVersionUID列,
  115. List<Field> fieldsNoSer=new ArrayList<Field>();
  116. for(int i=0;i<fields.length;i++){
  117. String fieldName=fields[i].getName();
  118. if(fieldName.equalsIgnoreCase("serialVersionUID")){
  119. continue;
  120. }else{
  121. fieldsNoSer.add(fields[i]);
  122. }
  123. }
  124. for(int i=0;i<fieldsNoSer.size();i++){
  125. HSSFCell cell = row.createCell(i);
  126. String fieldName=fieldsNoSer.get(i).getName();
  127. cell.setCellValue(getValue(nameAlias[nameAlias.length-1]+"."+fieldName));
  128. }
  129.  
  130. //iterating r number of rows
  131. for (int r=0;r < records.size(); r++ )
  132. {
  133. row = sheet.createRow(r+1);
  134. record=records.get(r);
  135. //table content
  136. for (int c=0;c < fieldsNoSer.size(); c++ )
  137. {
  138. HSSFCell cell = row.createCell(c);
  139. //加header,方法总变量的首字母大写
  140. String fieldName=fieldsNoSer.get(c).getName();
  141. try {
  142. Method method=cls.getDeclaredMethod("get"+fieldName.substring(0,1).toUpperCase()+fieldName.substring(1));
  143. Object ret=method.invoke(record);
  144. if(null!=ret){
  145. cell.setCellValue(method.invoke(record).toString());
  146. }
  147.  
  148. } catch (Exception e) {
  149. logger.info("write xls error,please check it");
  150. }
  151. }
  152. }
  153. FileOutputStream fileOut = new FileOutputStream(excelFileName);
  154.  
  155. //write this workbook to an Outputstream.
  156. wb.write(fileOut);
  157. fileOut.flush();
  158. fileOut.close();
  159. }
  160.  
  161. @SuppressWarnings({ "resource", "unused", "rawtypes" })
  162. public static void readXLSXFile() throws IOException
  163. {
  164. InputStream ExcelFileToRead = new FileInputStream("E:/source/Test1.xlsx");
  165. XSSFWorkbook wb = new XSSFWorkbook(ExcelFileToRead);
  166.  
  167. XSSFWorkbook test = new XSSFWorkbook();
  168.  
  169. XSSFSheet sheet = wb.getSheetAt(0);
  170. XSSFRow row;
  171. XSSFCell cell;
  172.  
  173. Iterator rows = sheet.rowIterator();
  174.  
  175. while (rows.hasNext())
  176. {
  177. row=(XSSFRow) rows.next();
  178. Iterator cells = row.cellIterator();
  179. while (cells.hasNext())
  180. {
  181. cell=(XSSFCell) cells.next();
  182.  
  183. if (cell.getCellType() == XSSFCell.CELL_TYPE_STRING)
  184. {
  185. System.out.print(cell.getStringCellValue()+" ");
  186. }
  187. else if(cell.getCellType() == XSSFCell.CELL_TYPE_NUMERIC)
  188. {
  189. System.out.print(cell.getNumericCellValue()+" ");
  190. }
  191. else
  192. {
  193. //U Can Handel Boolean, Formula, Errors
  194. }
  195. }
  196. System.out.println();
  197. }
  198.  
  199. }
  200.  
  201. @SuppressWarnings("resource")
  202. public static void writeXLSXFile() throws IOException {
  203.  
  204. String excelFileName = "E:/source/Test1.xlsx";//name of excel file
  205.  
  206. String sheetName = "Sheet1";//name of sheet
  207.  
  208. XSSFWorkbook wb = new XSSFWorkbook();
  209. XSSFSheet sheet = wb.createSheet(sheetName) ;
  210.  
  211. //iterating r number of rows
  212. for (int r=0;r < 5; r++ )
  213. {
  214. XSSFRow row = sheet.createRow(r);
  215.  
  216. //iterating c number of columns
  217. for (int c=0;c < 5; c++ )
  218. {
  219. XSSFCell cell = row.createCell(c);
  220.  
  221. cell.setCellValue("Cell "+r+" "+c);
  222. }
  223. }
  224.  
  225. FileOutputStream fileOut = new FileOutputStream(excelFileName);
  226.  
  227. //write this workbook to an Outputstream.
  228. wb.write(fileOut);
  229. fileOut.flush();
  230. fileOut.close();
  231. }
  232.  
  233. public static void main(String[] args) throws IOException, NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
  234. List<Log> logs=new ArrayList<Log>();
  235. for(int i=1;i<2;i++){
  236. Log log=new Log();
  237. log.setId(Long.parseLong(""+(i+6)));
  238. log.setUserId(Long.parseLong(""+i));
  239. log.setUserName("www"+i);
  240. logs.add(log);
  241. }
  242. writeXLSFile(logs,"E:/source/aa.xls");
  243.  
  244. }

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. 将double数据保留两位小数

    private double formatDouble(double number) { DecimalFormat df = new DecimalFormat("#.00"); ...

  2. HTML5的核心内容

    开发者可以放心地使用html5的理由 兼容性.HTML5在老版本的浏览器可以正常运行,同时支持HTML5的新浏览器也能正常运行HTML4,用HTML4创建出来的网站不是必须全部重建的. 实用性.HTM ...

  3. 记intel杯比赛中各种bug与debug【其五】:朴素贝叶斯分类器的实现和针对性的优化

    咱这个项目最主要的就是这个了 贝叶斯分类器用于做可以统计概率的二元分类 典型的例子就是垃圾邮件过滤 理论基础 对于贝叶斯算法,这里附上两个链接,便于理解: 朴素贝叶斯分类器的应用-阮一峰的网络日志 基 ...

  4. windows用xstart远程连接linux图形用户界面

    转载:https://blog.csdn.net/yabingshi_tech/article/details/51839379 双击xstart 输入:/usr/bin/xterm -ls -dis ...

  5. Linux Shell脚本编程-基础2

    命令退出状态码  bash每个命令,执行状态都有返回值 0表示成功 非0表示失败(1-255) $?特殊变量可以打印出上一条命令的状态返回值 脚本的状态返回值是脚本执行的最后一条命令 自定义脚本状态返 ...

  6. screen---管理会话

    Screen是一款由GNU计划开发的用于命令行终端切换的自由软件.用户可以通过该软件同时连接多个本地或远程的命令行会话,并在其间自由切换.GNU Screen可以看作是窗口管理器的命令行界面版本.它提 ...

  7. python 调试大法-大笨蛋的笔记

    说在前面 我觉得没有什么错误是调试器无法解决的,如果没有,那我再说一遍,如果有,那当我没说 一.抛出异常 可以通过 raise 语句抛出异常,使程序在我们已经知道的缺陷处停下,并进入到 except  ...

  8. Python组织文件 实践:将文件的不同版本备份为ZIP文件

    功能:备份文件夹.能将文件的不同版本备份下来,并且每个有不同的名字 #! python3 # backupToZip.py - 备份文件的不同版本到压缩文件中 import zipfile,os #f ...

  9. 题解 P3243 【[HNOI2015]菜肴制作】

    这道题看起来就是个裸的拓扑排序,抄上模板就能AC. 上面这种想法一看就不现实,然鹅我第一次还真就这么写了,然后被随意hack. 我们需要注意一句话: 现在,酒店希望能求出一个最优的菜肴的制作顺序,使得 ...

  10. 题解 P3605 【[USACO17JAN]Promotion Counting晋升者计数】

    这道题开10倍左右一直MLE+RE,然后尝试着开了20倍就A了...窒息 对于这道题目,我们考虑使用线段树合并来做. 所谓线段树合并,就是把结构相同的线段树上的节点的信息合在一起,合并的方式比较类似左 ...