2014-04-18 BY DINESH LEAVE A COMMENT

About a year or two ago I was working with finance team where they wanted to pull the credit card transactions for all the customer using various combinations. Ex –

– Get the credit card txns for today or certain date.

– Get the txns for customer who used Mastercard or Visa.

However they wanted this application to generate a Excel file and save it on their local machine so that they could prepare reports for our CEO. I used a Apache POI project to create jar files. This tutorial will walk you through the process of reading and writing excel sheet. So let’s see – How to read and write excel files in Java?

Brief History on Apache POI

Apache POI is a powerful Java library to work with different Microsoft Office file formats such as Excel, Power point, Visio, MS Word etc. The name POI was originally an acronym for Poor Obfuscation Implementation, referring humorously to the file formats that seemed deliberately obfuscated, but poorly, since they were successfully reverse-engineered.  In short, you can read / write MS Excel files using Java. In addition, you can read/write MS Word and MS PowerPoint files using Java. Apache POI is your Java Excel solution .

Apache POI can be used to create both old ( 2003-2008) and new( 2010 – newer) format. I think the newer jar file to create XLSX document is out of BETA phase now. Back when I used this POI it was still in Beta format.

So let’s see what does it entails to read /write Excel files in Java.

I am will be using Maven and IntelliJ to create my project, however you are welcome to useEclipseor Netbeans.

Apache POI dependencies

There are two different maven dependencies one for creating an older version of excel – XLS format and other for creating new version of Excel – XLSX format. I am listing both the dependencies here.

<dependencies>
<!– For Excel 2007 –>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.9</version>
</dependency>
</dependencies>

Create a new module in IntelliJ.

Add the dependency in your pom.xml

PAUSE & THINK: KEY POI CLASSES

Before we go ahead here’s quick primer on 3  key classes in POI.

  1. HSSF – Java implementation of the Excel ’97(-2007) file format. e.g. HSSFWorkbookHSSFSheet.
  2. XSSF –  Java implementation of the Excel 2007 OOXML (.xlsx) file format. e.g. XSSFWorkbookXSSFSheet.
  3. SXSSF – Used when very large spreadsheets have to be produced, and heap space is limited. e.g. SXSSFWorkbookSXSSFSheet.

There are other wide range of classes as well which can be used to manipulate the Excel sheet. Ex –  BuiltinFormatsConditionalFormattingRule,ComparisonOperator,CellStyleFontFormattingIndexedColorsPatternFormattingSheetConditionalFormatting. These used for formatting the sheet and formula evaluation.

HOW TO CREATE A NEW EXCEL SHEET

This involves the following steps.

So go ahead and create a new file called NewExcel.java

  1. package com.dinesh;
  2. import org.apache.poi.ss.usermodel.Cell;
  3. import org.apache.poi.ss.usermodel.Row;
  4. import org.apache.poi.xssf.usermodel.XSSFSheet;
  5. import org.apache.poi.xssf.usermodel.XSSFWorkbook;
  6.  
  7. import java.io.File;
  8. import java.io.FileNotFoundException;
  9. import java.io.FileOutputStream;
  10. import java.io.IOException;
  11. import java.util.HashMap;
  12. import java.util.Map;
  13. import java.util.Set;
  14. import java.util.TreeMap;
  15.  
  16. /**
  17. * Created by darora on 4/18/14.
  18. */
  19. public class NewExcel {
  20. public static void main(String[] args) {
  21. //Create a new Workbook
  22. XSSFWorkbook workbook = new XSSFWorkbook();
  23.  
  24. //Create a blank sheet
  25. XSSFSheet sheet = workbook.createSheet("Student data");
  26.  
  27. //Create the data for the excel sheet
  28. Map<string, object[]=""> data = new TreeMap<string, object[]="">();
  29. data.put("1", new Object[] {"ID", "FIRSTNAME", "LASTNAME"});
  30. data.put("2", new Object[] {1, "Randy", "Maven"});
  31. data.put("3", new Object[] {2, "Raymond", "Smith"});
  32. data.put("4", new Object[] {3, "Dinesh", "Arora"});
  33. data.put("5", new Object[] {4, "Barbra", "Klien"});
  34.  
  35. //Iterate over data and write it to the sheet
  36. Set keyset = data.keySet();
  37. int rownum = 0;
  38. for (String key : keyset)
  39. {
  40. Row row = sheet.createRow(rownum++);
  41. Object [] objArr = data.get(key);
  42. int cellnum = 0;
  43. for (Object obj : objArr)
  44. {
  45. Cell cell = row.createCell(cellnum++);
  46. if(obj instanceof String)
  47. cell.setCellValue((String)obj);
  48. else if(obj instanceof Integer)
  49. cell.setCellValue((Integer)obj);
  50. }
  51. }
  52. //Save the excel sheet
  53. try{
  54. FileOutputStream out = new FileOutputStream(new File("c:\Dinesh\javahabitExcelDemo.xlsx"));
  55. workbook.write(out);
  56. out.close();
  57. System.out.println("javahabitExcelDemo.xlsx Successfully created");
  58. } catch (FileNotFoundException e) {
  59. e.printStackTrace();
  60. } catch (IOException e) {
  61. e.printStackTrace();
  62. }
  63. }
  64.  
  65. }

OUTPUT

HOW TO READ A NEW EXCEL SHEET

So now that we have written an excel sheet. let’s try to read it back.

The steps involved are

  1. package com.dinesh;
  2.  
  3. import org.apache.poi.ss.usermodel.Cell;
  4. import org.apache.poi.ss.usermodel.Row;
  5. import org.apache.poi.xssf.usermodel.XSSFSheet;
  6. import org.apache.poi.xssf.usermodel.XSSFWorkbook;
  7.  
  8. import java.io.File;
  9. import java.io.FileInputStream;
  10. import java.io.FileNotFoundException;
  11. import java.io.IOException;
  12. import java.util.Iterator;
  13.  
  14. /**
  15. * Created by darora on 4/18/14.
  16. */
  17. public class ReadExcel {
  18. //Create Workbook instance from excel sheet
  19. public static void main(String[] args) {
  20. try {
  21. //Get the Excel File
  22. FileInputStream file = new FileInputStream(new File("c:\Dinesh\javahabitExcelDemo.xlsx"));
  23. XSSFWorkbook workbook = new XSSFWorkbook(file);
  24.  
  25. //Get the Desired sheet
  26. XSSFSheet sheet = workbook.getSheetAt(0);
  27.  
  28. //Increment over rows
  29. for (Row row : sheet) {
  30. //Iterate and get the cells from the row
  31. Iterator cellIterator = row.cellIterator();
  32. // Loop till you read all the data
  33. while (cellIterator.hasNext()) {
  34. Cell cell = cellIterator.next();
  35.  
  36. switch (cell.getCellType()) {
  37. case Cell.CELL_TYPE_NUMERIC:
  38. System.out.print(cell.getNumericCellValue() + "t");
  39. break;
  40. case Cell.CELL_TYPE_STRING:
  41. System.out.print(cell.getStringCellValue() + "t");
  42. break;
  43. }
  44. }
  45. System.out.println("");
  46. }
  47. file.close();
  48. } catch (FileNotFoundException e) {
  49. e.printStackTrace();
  50. } catch (IOException e) {
  51. e.printStackTrace();
  52. }
  53.  
  54. }
  55. }

OUTPUT

Using formulas in excel sheet

When working on excel sheets, we sometimes have to create cells which use formulas to calculate their values.  Apache POI has supports methods for adding formula to cells and evaluating the already present formula in the cells. Neat!!

So Let’s see an example on setting a formula cells in the excel sheet.

In this code we will try to calculate the Simple interest. Formula – Principal * Interest * Time.

  1. package com.dinesh;
  2.  
  3. import org.apache.poi.ss.usermodel.Row;
  4. import org.apache.poi.xssf.usermodel.XSSFSheet;
  5. import org.apache.poi.xssf.usermodel.XSSFWorkbook;
  6.  
  7. import java.io.File;
  8. import java.io.FileNotFoundException;
  9. import java.io.FileOutputStream;
  10. import java.io.IOException;
  11.  
  12. /**
  13. * Created by darora on 4/18/14.
  14. */
  15. public class CalculateFormula {
  16. public static void main(String[] args)
  17. {
  18. //Create the workbook
  19. XSSFWorkbook workbook = new XSSFWorkbook();
  20. //Create the sheet
  21. XSSFSheet sheet = workbook.createSheet("Calculate Simple Interest");
  22. //Create Wor Headers
  23. Row header = sheet.createRow(0);
  24. header.createCell(0).setCellValue("Principal");
  25. header.createCell(1).setCellValue("Interest");
  26. header.createCell(2).setCellValue("Time");
  27. header.createCell(3).setCellValue("OUTPUT (P * r * t)");
  28.  
  29. //Create the Rows
  30. Row dataRow = sheet.createRow(1);
  31. dataRow.createCell(0).setCellValue(1000d);
  32. dataRow.createCell(1).setCellValue(12.00);
  33. dataRow.createCell(2).setCellValue(6d);
  34. dataRow.createCell(3).setCellFormula("A2*B2*C2");
  35.  
  36. //Save the File
  37. try {
  38. FileOutputStream out = new FileOutputStream(new File("c:\Dinesh\javahabitformulaDemo.xlsx"));
  39. workbook.write(out);
  40. out.close();
  41. System.out.println("Excel File with formla is created!");
  42.  
  43. } catch (FileNotFoundException e) {
  44. e.printStackTrace();
  45. } catch (IOException e) {
  46. e.printStackTrace();
  47. }
  48. }
  49. }

OUTPUT

So experiment your way with this jar file and do post your comments and suggestions on topics you had like to see in my future posts.

AUTHOR

I am Dinesh Arora, Java Developer, Go getter, Father and passionate about DIY and Blogging. Connect with me through twitter

 

Read / Write Excel file in Java using Apache POI的更多相关文章

  1. Apache POI – Reading and Writing Excel file in Java

    来源于:https://www.mkyong.com/java/apache-poi-reading-and-writing-excel-file-in-java/ In this article, ...

  2. java使用Apache POI操作excel文件

    官方介绍 HSSF is the POI Project's pure Java implementation of the Excel '97(-2007) file format. XSSF is ...

  3. Java中用Apache POI生成excel和word文档

    概述: 近期在做项目的过程中遇到了excel的数据导出和word的图文表报告的导出功能.最后决定用Apache POI来完毕该项功能.本文就项目实现过程中的一些思路与代码与大家共享.同一时候.也作为自 ...

  4. Java 使用Apache POI读取和写入Excel表格

    1,引入所用的包 <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxm ...

  5. java 通过Apache poi导出excel代码demo实例

    package com.zuidaima.excel.util; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutput ...

  6. Java使用Apache POI进行Excel导入和导出

    Manve依赖 <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml --> <dependency> ...

  7. Java利用Apache poi导出图表

    jar compile('org.apache.poi:poi:4.0.1') compile('org.apache.poi:poi-scratchpad:4.0.1') compile('org. ...

  8. Java利用Apache POI将数据库数据导出为excel

    将数据库中的数据导出为excel文件,供其他人查看 public class POITest { public static void main(String[] args) { POITest te ...

  9. How to Read, Write XLSX File in Java - Apach POI Example---reference

    No matter how Microsoft is doing in comparison with Google, Microsoft Office is still the most used ...

随机推荐

  1. 随笔2 PAT1001.A+B Format (20)

    1001.A+B Format(20) 题目链接 1001.A+B Format (20) C++ 代码 第一次使用markdown,还不是很习惯,现在努力的在适应它 首先这道题我们很容易就可以读懂题 ...

  2. C#: 方法的默认参数

    大家都知道在C++中,我们可以为方法的参数指定一个默认值,像这样: void foo(int i = 100); 当我们以这种形式调用方法的时候: foo(); 实际上参数i被赋于了默认值,所以相当于 ...

  3. MySQL重置密码(OSX)

    1.停止MySQL的服务 sudo /Library/StartupItems/MySQLCOM/MySQLCOM stop   2.cd /usr/local/mysql/bin ./mysqld_ ...

  4. JSP文件下载时文件名在ie和firefox下面文件名不一致极其超链接中文乱码的问题的改进

    response.setContentType("application/octet-stream;charset=UTF-8"); fileName=java.net.URLEn ...

  5. centOS安装openoffice

    centOS安装openoffice的方法: yum install openoffice.org-writer yum install openoffice.org-calc yum install ...

  6. android 小方法

    小方法 1.获取屏幕分辨率: public class BaseTools { public static int getWindowWidth(Context context) { // 获取屏幕分 ...

  7. 解决WebService 中泛型接口不能序列化问题

    本来要定义WebServices 方法返回一泛型接口集合IList,系统提示不能序列化泛型接口集合  1   [WebMethod]  2         public IList<Employ ...

  8. EasyMock问题总结

    1. java.lang.IllegalStateException: missing behavior definition for the preceding method call getBid ...

  9. Linux下 如何正确配置 Nginx + PHP

    假设我们用PHP实现了一个前端控制器,或者直白点说就是统一入口:把PHP请求都发送到同一个文件上,然后在此文件里通过解析「REQUEST_URI」实现路由. 一般这样配置 此时很多教程会教大家这样配置 ...

  10. 前向否定界定符 python正则表达式不匹配某个字符串 以及无捕获组和命名组(转)

    [编辑] 无捕获组和命名组 精心设计的 REs 也许会用很多组,既可以捕获感兴趣的子串,又可以分组和结构化 RE 本身.在复杂的 REs 里,追踪组号变得困难.有两个功能可以对这个问题有所帮助.它们也 ...