【问题标题】:How to read and write excel file如何读写excel文件
【发布时间】:2009-10-04 10:54:38
【问题描述】:

我想从 Java 中读取和写入一个包含 3 列和 N 行的 Excel 文件,在每个单元格中打印一个字符串。谁能给我简单的代码sn-p?我需要使用任何外部库还是 Java 有内置支持?

我想做以下事情:

for(i=0; i <rows; i++)
     //read [i,col1] ,[i,col2], [i,col3]

for(i=0; i<rows; i++)
    //write [i,col1], [i,col2], [i,col3]

【问题讨论】:

  • 使用GemBox.Spreadsheet for Java 这很简单,您只需遍历工作表中的行和一行中分配的单元格,然后在每个单元格上调用ExcelCell.getValue()。例如,查看这个reading 示例,也可以查看this 示例。

标签: java excel


【解决方案1】:

试试Apache POI HSSF。下面是一个如何读取 excel 文件的示例:

try {
    POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(file));
    HSSFWorkbook wb = new HSSFWorkbook(fs);
    HSSFSheet sheet = wb.getSheetAt(0);
    HSSFRow row;
    HSSFCell cell;

    int rows; // No of rows
    rows = sheet.getPhysicalNumberOfRows();

    int cols = 0; // No of columns
    int tmp = 0;

    // This trick ensures that we get the data properly even if it doesn't start from first few rows
    for(int i = 0; i < 10 || i < rows; i++) {
        row = sheet.getRow(i);
        if(row != null) {
            tmp = sheet.getRow(i).getPhysicalNumberOfCells();
            if(tmp > cols) cols = tmp;
        }
    }

    for(int r = 0; r < rows; r++) {
        row = sheet.getRow(r);
        if(row != null) {
            for(int c = 0; c < cols; c++) {
                cell = row.getCell((short)c);
                if(cell != null) {
                    // Your code here
                }
            }
        }
    }
} catch(Exception ioe) {
    ioe.printStackTrace();
}

在文档页面上,您还提供了如何写入 excel 文件的示例。

【讨论】:

  • row.getCell((short)c);已弃用,我想我必须改用 int。
  • 在我尝试使用此代码时,我发现HSSFSheetgetPhysicalNumberOfRows() 方法似乎返回了非空行的数量(对我来说这不是“物理”的意思)。因此,如果您的 excel 文件有很多空行(即出于格式化原因),使用rows = sheet.getLastRowNum(); 可能会更幸运。这也应该意味着您可以从第一个循环中删除技巧(见评论):for(int i = 0; i &lt;= rows; i++) {(注意从&lt;&lt;= 的变化)。
  • 很抱歉再次挖掘,但我遇到了同样的问题,假设您有 3 列名称、出生日期、性别。如何通过阅读此代码将 3 添加到单独的 Vector 中?
  • 尝试使用 Workbook 而不是 HSSFWorkbook。它同时支持 HSSF (.xls) 和 XSSF (.xlsx)。
【解决方案2】:

Apache POI 可以为您做到这一点。特别是HSSF 模块。 quick guide 是最有用的。以下是您想要做的事情的方法 - 具体来说是创建一个工作表并将其写出来。

Workbook wb = new HSSFWorkbook();
//Workbook wb = new XSSFWorkbook();
CreationHelper createHelper = wb.getCreationHelper();
Sheet sheet = wb.createSheet("new sheet");

// Create a row and put some cells in it. Rows are 0 based.
Row row = sheet.createRow((short)0);
// Create a cell and put a value in it.
Cell cell = row.createCell(0);
cell.setCellValue(1);

// Or do it on one line.
row.createCell(1).setCellValue(1.2);
row.createCell(2).setCellValue(
createHelper.createRichTextString("This is a string"));
row.createCell(3).setCellValue(true);

// Write the output to a file
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
wb.write(fileOut);
fileOut.close();

【讨论】:

  • 我们可以在没有任何框架的帮助下用普通的 java/spring 来做吗?
  • 如果你使用的是 Spring,它就不是普通的 Java。我认为如果您想阅读这些文件,那么 POI 是前进的方向
【解决方案3】:

首先将所有这些jar文件添加到你的项目类路径中:

  1. poi-scratchpad-3.7-20101029
  2. poi-3.2-FINAL-20081019
  3. poi-3.7-20101029
  4. poi-examples-3.7-20101029
  5. poi-ooxml-3.7-20101029
  6. poi-ooxml-schemas-3.7-20101029
  7. xmlbeans-2.3.0
  8. dom4j-1.6.1

excel文件写入代码:

public static void main(String[] args) {
    //Blank workbook
    XSSFWorkbook workbook = new XSSFWorkbook();

    //Create a blank sheet
    XSSFSheet sheet = workbook.createSheet("Employee Data");

    //This data needs to be written (Object[])
    Map<String, Object[]> data = new TreeMap<String, Object[]>();
    data.put("1", new Object[]{"ID", "NAME", "LASTNAME"});
    data.put("2", new Object[]{1, "Amit", "Shukla"});
    data.put("3", new Object[]{2, "Lokesh", "Gupta"});
    data.put("4", new Object[]{3, "John", "Adwards"});
    data.put("5", new Object[]{4, "Brian", "Schultz"});

    //Iterate over data and write to sheet
    Set<String> keyset = data.keySet();

    int rownum = 0;
    for (String key : keyset) 
    {
        //create a row of excelsheet
        Row row = sheet.createRow(rownum++);

        //get object array of prerticuler key
        Object[] objArr = data.get(key);

        int cellnum = 0;

        for (Object obj : objArr) 
        {
            Cell cell = row.createCell(cellnum++);
            if (obj instanceof String) 
            {
                cell.setCellValue((String) obj);
            }
            else if (obj instanceof Integer) 
            {
                cell.setCellValue((Integer) obj);
            }
        }
    }
    try 
    {
        //Write the workbook in file system
        FileOutputStream out = new FileOutputStream(new File("C:\\Documents and Settings\\admin\\Desktop\\imp data\\howtodoinjava_demo.xlsx"));
        workbook.write(out);
        out.close();
        System.out.println("howtodoinjava_demo.xlsx written successfully on disk.");
    } 
    catch (Exception e)
    {
        e.printStackTrace();
    }
}

读取excel文件的代码

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

public static void main(String[] args) {
    try {
        FileInputStream file = new FileInputStream(new File("C:\\Documents and Settings\\admin\\Desktop\\imp data\\howtodoinjava_demo.xlsx"));

        //Create Workbook instance holding reference to .xlsx file
        XSSFWorkbook workbook = new XSSFWorkbook(file);

        //Get first/desired sheet from the workbook
        XSSFSheet sheet = workbook.getSheetAt(0);

        //Iterate through each rows one by one
        Iterator<Row> rowIterator = sheet.iterator();
        while (rowIterator.hasNext())
        {
            Row row = rowIterator.next();
            //For each row, iterate through all the columns
            Iterator<Cell> cellIterator = row.cellIterator();

            while (cellIterator.hasNext()) 
            {
                Cell cell = cellIterator.next();
                //Check the cell type and format accordingly
                switch (cell.getCellType()) 
                {
                    case Cell.CELL_TYPE_NUMERIC:
                        System.out.print(cell.getNumericCellValue() + "\t");
                        break;
                    case Cell.CELL_TYPE_STRING:
                        System.out.print(cell.getStringCellValue() + "\t");
                        break;
                }
            }
            System.out.println("");
        }
        file.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

【讨论】:

    【解决方案4】:

    您也可以考虑JExcelApi。我发现它比 POI 设计得更好。有教程here

    【讨论】:

    • 我尝试访问教程页面。它似乎已被删除。
    • JExcelApi 适用于旧的(直到 Excel 2003)二进制 .xls 文件。 Apache POI-HSSF 处理相同的旧 .xls,而 Apache POI-XSSF 使用新的 (Excel 2007-) .xlsx
    • 缺点是只支持处理.xls(1997-2003)格式的Excel文件。
    【解决方案5】:

    有一个新的简单且非常酷的工具(10x to Kfir):xcelite

    写:

    public class User { 
    
      @Column (name="Firstname")
      private String firstName;
    
      @Column (name="Lastname")
      private String lastName;
    
      @Column
      private long id; 
    
      @Column
      private Date birthDate; 
    }
    
    Xcelite xcelite = new Xcelite();    
    XceliteSheet sheet = xcelite.createSheet("users");
    SheetWriter<User> writer = sheet.getBeanWriter(User.class);
    List<User> users = new ArrayList<User>();
    // ...fill up users
    writer.write(users); 
    xcelite.write(new File("users_doc.xlsx"));
    

    阅读:

    Xcelite xcelite = new Xcelite(new File("users_doc.xlsx"));
    XceliteSheet sheet = xcelite.getSheet("users");
    SheetReader<User> reader = sheet.getBeanReader(User.class);
    Collection<User> users = reader.read();
    

    【讨论】:

      【解决方案6】:

      为了读取 xlsx 文件,我们可以使用 Apache POI libs 试试这个:

      public static void readXLSXFile() throws IOException
          {
              InputStream ExcelFileToRead = new FileInputStream("C:/Test.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();
              }
      
          }
      

      【讨论】:

        【解决方案7】:

        .csv 或 POI 肯定会这样做,但您应该注意 Andy Khan 的 JExcel。我认为它是迄今为止最好的用于处理 Excel 的 Java 库。

        【讨论】:

        • 它是商业的!
        • 距离原始答案已有 12 年。或者在 2009 年开源。
        【解决方案8】:

        一个简单的 CSV 文件就足够了

        【讨论】:

        • 请注意,您必须在写入 CSV 的字符串中转义逗号。
        • 确实 CSV 就足够了。如果您的字段没有逗号,那么打印字段和逗号可能是最简单的。否则,您可能需要使用commons.apache.org/sandbox/csv
        • 我不确定 CSV 是否足够,因为这个问题专门说“读取”和“写入”一个 Excel 文件。他也许可以摆脱 CSV,但这不是他要问的。
        • 某些国际版本的 Excel 使用分号而不是逗号作为分隔符。这也增加了复杂性
        • 如果输出包含日期 CSV 可能太简单了。
        【解决方案9】:
        String path="C:\\Book2.xlsx";
        try {
        
                File f = new File( path );
                Workbook wb = WorkbookFactory.create(f);
                Sheet mySheet = wb.getSheetAt(0);
                Iterator<Row> rowIter = mySheet.rowIterator();
                for ( Iterator<Row> rowIterator = mySheet.rowIterator() ;rowIterator.hasNext(); )
                {
                    for (  Iterator<Cell> cellIterator = ((Row)rowIterator.next()).cellIterator() ; cellIterator.hasNext() ;  ) 
                    {
                        System.out.println ( ( (Cell)cellIterator.next() ).toString() );
                    }
                    System.out.println( " **************************************************************** ");
                }
            } catch ( Exception e )
            {
                System.out.println( "exception" );
                e.printStackTrace();
            }
        

        并确保已将罐子 poi 和 poi-ooxml (org.apache.poi) 添加到您的项目中

        【讨论】:

          【解决方案10】:

          为了从 .xlsx 工作簿中读取数据,我们需要使用 XSSFworkbook 类。

          XSSFWorkbook xlsxBook = new XSSFWorkbook(fis);

          XSSFSheet sheet = xlsxBook.getSheetAt(0);

          我们需要使用 Apache-poi 3.9 @http://poi.apache.org/

          有关示例的详细信息,请访问 :http://java-recent.blogspot.in

          【讨论】:

          • 使用 Apache POI,您需要用于 XLS 的 HSSF 模块和用于 XLSX 格式的 XSSF 模块,GemBox.Spreadsheet for Java 两种格式统一到同一个模块中,并用相同的 ExcelFile 类型表示。
          【解决方案11】:

          当然,您会发现下面的代码非常实用且易于阅读和编写。这是一个 util 类,您可以在 main 方法中使用它,然后您可以使用以下所有方法。

               public class ExcelUtils {
               private static XSSFSheet ExcelWSheet;
               private static XSSFWorkbook ExcelWBook;
               private static XSSFCell Cell;
               private static XSSFRow Row;
               File fileName = new File("C:\\Users\\satekuma\\Pro\\Fund.xlsx");
               public void setExcelFile(File Path, String SheetName) throws Exception                
          
              try {
                  FileInputStream ExcelFile = new FileInputStream(Path);
                  ExcelWBook = new XSSFWorkbook(ExcelFile);
                  ExcelWSheet = ExcelWBook.getSheet(SheetName);
              } catch (Exception e) {
                  throw (e);
              }
          
          }
          
          
                public static String getCellData(int RowNum, int ColNum) throws Exception {
          
              try {
                  Cell = ExcelWSheet.getRow(RowNum).getCell(ColNum);
                  String CellData = Cell.getStringCellValue();
                  return CellData;
              } catch (Exception e) {
          
                  return "";
          
              }
          
          }
          public static void setCellData(String Result, int RowNum, int ColNum, File Path) throws Exception {
          
              try {
                  Row = ExcelWSheet.createRow(RowNum - 1);
                  Cell = Row.createCell(ColNum - 1);
                  Cell.setCellValue(Result);
                  FileOutputStream fileOut = new FileOutputStream(Path);
                  ExcelWBook.write(fileOut);
                  fileOut.flush();
                  fileOut.close();
              } catch (Exception e) {
          
                  throw (e);
          
              }
          
          }
          
          }
          

          【讨论】:

            【解决方案12】:

            使用spring apache poi repo

            if (fileName.endsWith(".xls")) {
            
            
            
            File myFile = new File("file location" + fileName);
                            FileInputStream fis = new FileInputStream(myFile);
            
                            org.apache.poi.ss.usermodel.Workbook workbook = null;
                            try {
                                workbook = WorkbookFactory.create(fis);
                            } catch (InvalidFormatException e) {
            
                                e.printStackTrace();
                            }
            
            
                            org.apache.poi.ss.usermodel.Sheet sheet = workbook.getSheetAt(0);
            
            
                            Iterator<Row> rowIterator = sheet.iterator();
            
            
                            while (rowIterator.hasNext()) {
                                Row row = rowIterator.next();
            
                                Iterator<Cell> cellIterator = row.cellIterator();
                                while (cellIterator.hasNext()) {
            
                                    Cell cell = cellIterator.next();
                                    switch (cell.getCellType()) {
                                    case Cell.CELL_TYPE_STRING:
                                        System.out.print(cell.getStringCellValue());
                                        break;
                                    case Cell.CELL_TYPE_BOOLEAN:
                                        System.out.print(cell.getBooleanCellValue());
                                        break;
                                    case Cell.CELL_TYPE_NUMERIC:
                                        System.out.print(cell.getNumericCellValue());
                                        break;
                                    }
                                    System.out.print(" - ");
                                }
                                System.out.println();
                            }
                        }
            

            【讨论】:

              【解决方案13】:

              我编辑了投票最多的一个,因为它没有完全计算空白列或行,所以这是我测试过的代码,现在可以获取 Excel 文件任何部分中的任何单元格。现在你也可以在填充列之间有空白列,它会读取它们

                try {
              POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(Dir));
              HSSFWorkbook wb = new HSSFWorkbook(fs);
              HSSFSheet sheet = wb.getSheetAt(0);
              HSSFRow row;
              HSSFCell cell;
              
              int rows; // No of rows
              rows = sheet.getPhysicalNumberOfRows();
              
              int cols = 0; // No of columns
              int tmp = 0;
              int cblacks=0;
              
              // This trick ensures that we get the data properly even if it doesn't start from first few rows
              for(int i = 0; i <= 10 || i <= rows; i++) {
                  row = sheet.getRow(i);
                  if(row != null) {
                      tmp = sheet.getRow(i).getPhysicalNumberOfCells();
                      if(tmp >= cols) cols = tmp;else{rows++;cblacks++;}
                  }
              
                  cols++;
              }
              cols=cols+cblacks;
              for(int r = 0; r < rows; r++) {
                  row = sheet.getRow(r);
                  if(row != null) {
                      for(int c = 0; c < cols; c++) {
                          cell = row.getCell(c);
                          if(cell != null) {
                              System.out.print(cell+"\n");//Your Code here
                          }
                      }
                  }
              }} catch(Exception ioe) {
              ioe.printStackTrace();}
              

              【讨论】:

                【解决方案14】:

                如果列号不同,您可以使用它

                package com.org.tests;
                import org.apache.poi.xssf.usermodel.*;
                import java.io.FileInputStream;
                import java.io.IOException;
                
                public class ExcelSimpleTest 
                {   
                    String path;
                    public FileInputStream fis = null;
                    private XSSFWorkbook workbook = null;
                    private XSSFSheet sheet = null;
                    private XSSFRow row   =null;
                    private XSSFCell cell = null;
                
                    public ExcelSimpleTest() throws IOException
                    {
                        path = System.getProperty("user.dir")+"\\resources\\Book1.xlsx";
                        fis = new FileInputStream(path); 
                        workbook = new XSSFWorkbook(fis);
                        sheet = workbook.getSheetAt(0);
                    }
                    public void ExelWorks()
                    {
                        int index = workbook.getSheetIndex("Sheet1");
                        sheet = workbook.getSheetAt(index);
                        int rownumber=sheet.getLastRowNum()+1;  
                
                        for (int i=1; i<rownumber; i++ )
                        {
                            row = sheet.getRow(i);
                            int colnumber = row.getLastCellNum();
                            for (int j=0; j<colnumber; j++ )
                            {
                                cell = row.getCell(j);
                                System.out.println(cell.getStringCellValue());
                            }
                        }
                    }   
                    public static void main(String[] args) throws IOException 
                    {
                        ExcelSimpleTest excelwork = new ExcelSimpleTest();
                        excelwork.ExelWorks();
                    }
                }
                

                对应的maven依赖可以找到here

                【讨论】:

                • 变化,变化过度
                【解决方案15】:

                另一种读取/写入 Excel 文件的方法是使用Windmill。它提供了一个流畅的 API 来处理 Excel 和 CSV 文件。

                导入数据

                try (Stream<Row> rowStream = Windmill.parse(FileSource.of(new FileInputStream("myFile.xlsx")))) {
                  rowStream
                    // skip the header row that contains the column names
                    .skip(1)
                    .forEach(row -> {
                      System.out.println(
                        "row n°" + row.rowIndex()
                        + " column 'User login' value : " + row.cell("User login").asString()
                        + " column n°3 number value : " + row.cell(2).asDouble().value() // index is zero-based
                      );
                    });
                }
                

                导出数据

                Windmill
                  .export(Arrays.asList(bean1, bean2, bean3))
                  .withHeaderMapping(
                    new ExportHeaderMapping<Bean>()
                      .add("Name", Bean::getName)
                      .add("User login", bean -> bean.getUser().getLogin())
                  )
                  .asExcel()
                  .writeTo(new FileOutputStream("Export.xlsx"));
                

                【讨论】:

                  【解决方案16】:

                  您需要 Apache POI 库,下面的代码应该可以帮助您

                      import java.io.File;
                      import java.io.FileInputStream;
                      import java.io.FileNotFoundException;
                      import java.io.FileOutputStream;
                      import java.io.IOException;
                      import java.util.ArrayList;
                      import java.util.List;
                      import java.util.Iterator;
                      //*************************************************************
                      import org.apache.poi.ss.usermodel.Sheet;
                      import org.apache.poi.ss.usermodel.Cell;
                      import org.apache.poi.ss.usermodel.Row;
                      import org.apache.poi.ss.usermodel.Workbook;
                      import org.apache.poi.xssf.usermodel.XSSFSheet;
                      import org.apache.poi.xssf.usermodel.XSSFWorkbook;
                  
                      //*************************************************************
                     public class AdvUse {
                  
                      private static Workbook wb ; 
                      private static Sheet sh ; 
                      private static FileInputStream fis ; 
                      private static FileOutputStream fos  ; 
                      private static Row row  ; 
                      private static Cell cell  ;
                      private static String ExcelPath ; 
                  
                      //*************************************************************
                      public static void setEcxelFile(String ExcelPath, String SheetName) throws Exception {
                      try {
                     File f= new File(ExcelPath); 
                     if(!f.exists()){
                         f.createNewFile();
                         System.out.println("File not Found so created");
                     }
                  
                      fis = new FileInputStream("./testData.xlsx");
                      wb = WorkbookFactory.create(fis); 
                      sh = wb.getSheet("SheetName");
                      if(sh == null){
                          sh = wb.getSheet(SheetName); 
                      }
                      }catch(Exception e)
                      {System.out.println(e.getMessage());
                      }
                      }
                  
                        //*************************************************************
                        public static void setCellData(String text , int rowno , int colno){
                      try{
                          row = sh.getRow(rowno);
                          if(row == null){
                              row = sh.createRow(rowno);
                          }
                          cell = row.getCell(colno);
                          if(cell!=null){
                              cell.setCellValue(text);
                  
                          }
                          else{
                              cell = row.createCell(colno);
                              cell.setCellValue(text);
                  
                          }
                          fos = new FileOutputStream(ExcelPath);
                          wb.write(fos);
                          fos.flush();
                          fos.close();
                      }catch(Exception e){
                          System.out.println(e.getMessage());
                      }
                      }
                  
                        //*************************************************************
                        public static String getCellData(int rowno , int colno){
                          try{
                  
                              cell = sh.getRow(rowno).getCell(colno); 
                              String CellData = null ;
                              switch(cell.getCellType()){
                              case  STRING :
                                  CellData = cell.getStringCellValue();
                                 break ; 
                              case NUMERIC : 
                                  CellData = Double.toString(cell.getNumericCellValue());
                                  if(CellData.contains(".o")){
                                      CellData = CellData.substring(0,CellData.length()-2);
                  
                                  }
                              break ; 
                              case BLANK : 
                              CellData = ""; break ; 
                  
                              }
                              return CellData;
                          }catch(Exception e){return ""; }
                      }
                  
                         //*************************************************************
                        public static int getLastRow(){
                          return sh.getLastRowNum();
                      }
                  

                  【讨论】:

                    【解决方案17】:

                    你不能同时读写同一个文件(Read-write lock)。但是,我们可以对临时数据(即输入/输出流)进行并行操作。仅在关闭输入流后才将数据写入文件。应遵循以下步骤。

                    • 打开文件到输入流
                    • 将同一文件打开到输出流
                    • 阅读并进行处理
                    • 将内容写入输出流。
                    • 关闭读取/输入流,关闭文件
                    • 关闭输出流,关闭文件。

                    Apache POI - 读/写相同的 excel 示例

                    import java.io.File;
                    import java.io.FileInputStream;
                    import java.io.FileNotFoundException;
                    import java.io.FileOutputStream;
                    import java.io.IOException;
                    import java.sql.Date;
                    import java.util.HashMap;
                    import java.util.Iterator;
                    import java.util.Map;
                    import java.util.Set;
                    
                    import org.apache.poi.ss.usermodel.Cell;
                    import org.apache.poi.ss.usermodel.Row;
                    import org.apache.poi.xssf.usermodel.XSSFSheet;
                    import org.apache.poi.xssf.usermodel.XSSFWorkbook;
                    
                    
                    public class XLSXReaderWriter {
                    
                        public static void main(String[] args) {
                    
                            try {
                                File excel = new File("D://raju.xlsx");
                                FileInputStream fis = new FileInputStream(excel);
                                XSSFWorkbook book = new XSSFWorkbook(fis);
                                XSSFSheet sheet = book.getSheetAt(0);
                    
                                Iterator<Row> itr = sheet.iterator();
                    
                                // Iterating over Excel file in Java
                                while (itr.hasNext()) {
                                    Row row = itr.next();
                    
                                    // Iterating over each column of Excel file
                                    Iterator<Cell> cellIterator = row.cellIterator();
                                    while (cellIterator.hasNext()) {
                    
                                        Cell cell = cellIterator.next();
                    
                                        switch (cell.getCellType()) {
                                        case Cell.CELL_TYPE_STRING:
                                            System.out.print(cell.getStringCellValue() + "\t");
                                            break;
                                        case Cell.CELL_TYPE_NUMERIC:
                                            System.out.print(cell.getNumericCellValue() + "\t");
                                            break;
                                        case Cell.CELL_TYPE_BOOLEAN:
                                            System.out.print(cell.getBooleanCellValue() + "\t");
                                            break;
                                        default:
                    
                                        }
                                    }
                                    System.out.println("");
                                }
                    
                                // writing data into XLSX file
                                Map<String, Object[]> newData = new HashMap<String, Object[]>();
                                newData.put("1", new Object[] { 1d, "Raju", "75K", "dev",
                                        "SGD" });
                                newData.put("2", new Object[] { 2d, "Ramesh", "58K", "test",
                                        "USD" });
                                newData.put("3", new Object[] { 3d, "Ravi", "90K", "PMO",
                                        "INR" });
                    
                                Set<String> newRows = newData.keySet();
                                int rownum = sheet.getLastRowNum();
                    
                                for (String key : newRows) {
                                    Row row = sheet.createRow(rownum++);
                                    Object[] objArr = newData.get(key);
                                    int cellnum = 0;
                                    for (Object obj : objArr) {
                                        Cell cell = row.createCell(cellnum++);
                                        if (obj instanceof String) {
                                            cell.setCellValue((String) obj);
                                        } else if (obj instanceof Boolean) {
                                            cell.setCellValue((Boolean) obj);
                                        } else if (obj instanceof Date) {
                                            cell.setCellValue((Date) obj);
                                        } else if (obj instanceof Double) {
                                            cell.setCellValue((Double) obj);
                                        }
                                    }
                                }
                    
                                // open an OutputStream to save written data into Excel file
                                FileOutputStream os = new FileOutputStream(excel);
                                book.write(os);
                                System.out.println("Writing on Excel file Finished ...");
                    
                                // Close workbook, OutputStream and Excel file to prevent leak
                                os.close();
                                book.close();
                                fis.close();
                    
                            } catch (FileNotFoundException fe) {
                                fe.printStackTrace();
                            } catch (IOException ie) {
                                ie.printStackTrace();
                            }
                        }
                    }
                    

                    【讨论】:

                      【解决方案18】:

                      请使用 Apache POI 库并尝试一下。

                          try
                          {
                              FileInputStream x = new FileInputStream(new File("/Users/rajesh/Documents/rajesh.xls"));
                      
                              //Create Workbook instance holding reference to .xlsx file
                              Workbook workbook = new HSSFWorkbook(x);
                      
                              //Get first/desired sheet from the workbook
                              Sheet sheet = workbook.getSheetAt(0);
                      
                              //Iterate through each rows one by one
                              for (Iterator<Row> iterator = sheet.iterator(); iterator.hasNext();) {
                                  Row row = (Row) iterator.next();
                                  for (Iterator<Cell> iterator2 = row.iterator(); iterator2
                                          .hasNext();) {
                                      Cell cell = (Cell) iterator2.next();
                                      System.out.println(cell.getStringCellValue());              
                                  }               
                              }         
                              x.close();
                          }
                          catch (Exception e)
                          {
                              e.printStackTrace();
                          }
                         }
                      }
                      

                      【讨论】:

                        【解决方案19】:

                        使用 apache poi 4.1.2 时。细胞类型发生了一些变化。下面是一个例子

                            try {
                                File excel = new File("/home/name/Downloads/bb.xlsx");
                                FileInputStream fis = new FileInputStream(excel);
                                XSSFWorkbook book = new XSSFWorkbook(fis);
                                XSSFSheet sheet = book.getSheetAt(0);
                        
                                Iterator<Row> itr = sheet.iterator();
                        
                                // Iterating over Excel file in Java
                                while (itr.hasNext()) {
                                    Row row = itr.next();
                        
                                    Iterator<Cell> cellIterator = row.cellIterator();
                                    while (cellIterator.hasNext()) {
                        
                        
                        
                                        Cell cell = cellIterator.next();
                        
                        
                        
                                        switch (cell.getCellType()) {
                                        case STRING:
                                            System.out.print(cell.getStringCellValue() + "\t");
                                            break;
                                        case NUMERIC:
                                            System.out.print(cell.getNumericCellValue() + "\t");
                                            break;
                                        case BOOLEAN:
                                            System.out.print(cell.getBooleanCellValue() + "\t");
                                            break;
                                        default:
                        
                        
                                        }
                                    }
                                    System.out.println("");}
                                }catch (Exception e) {
                                    // TODO: handle exception
                                    e.printStackTrace();
                                }
                        

                        【讨论】:

                          【解决方案20】:

                          如果您选择第三方库选项,请尝试使用Aspose.Cells API,它使 Java 应用程序无需 Microsoft Excel 即可高效地创建(读/写)和管理 Excel 电子表格。

                          例如

                          示例代码:

                          1.

                          //Load sample workbook
                          Workbook wb = new Workbook(dirPath + "sample.xlsx");
                          
                          //Access first worksheet
                          Worksheet ws = wb.getWorksheets().get(0);
                          
                          //Access cells iterator
                          Iterator itrat = ws.getCells().iterator();
                          
                          //Print cells name in iterator
                          while(itrat.hasNext())
                          {
                              Cell cell = (Cell)itrat.next();
                          
                              System.out.println(cell.getName() + ": " + cell.getStringValue().trim());
                          }
                          
                          Workbook book = new Workbook("sample.xlsx");
                          Worksheet sheet = book.getWorksheets().get(0);
                          Range range = sheet.getCells().getMaxDisplayRange();//You may also create your desired range (in the worksheet) using, e.g sheet.getCells().createRange("A1", "J11");
                          Iterator rangeIterator = range.iterator();
                          while(rangeIterator.hasNext())
                          {
                          Cell cell = (Cell)rangeIterator.next();
                          //your code goes here.
                          }
                          

                          希望,这有点帮助。

                          PS。我在 Aspose 担任支持开发人员/宣传员。

                          【讨论】:

                            【解决方案21】:

                            如果您需要对 Java 中的办公文档做更多的事情,请使用前面提到的 POI。

                            对于像您要求的那样简单地读取/写入 excel 文档,您可以使用 CSV 格式(也如上所述):

                            import java.io.BufferedReader;
                            import java.io.FileReader;
                            import java.io.FileWriter;
                            import java.io.IOException;
                            import java.io.PrintWriter;
                            import java.util.Scanner;
                            
                            public class CsvWriter {
                             public static void main(String args[]) throws IOException {
                            
                              String fileName = "test.xls";
                            
                              PrintWriter out = new PrintWriter(new FileWriter(fileName));
                              out.println("a,b,c,d");
                              out.println("e,f,g,h");
                              out.println("i,j,k,l");
                              out.close();
                            
                              BufferedReader in = new BufferedReader(new FileReader(fileName));
                              String line = null;
                              while ((line = in.readLine()) != null) {
                            
                               Scanner scanner = new Scanner(line);
                               String sep = "";
                               while (scanner.hasNext()) {
                                System.out.println(sep + scanner.next());
                                sep = ",";
                               }
                              }
                              in.close();
                             }
                            }
                            

                            【讨论】:

                              【解决方案22】:

                              这会将 JTable 写入一个制表符分隔的文件,该文件可以轻松导入 Excel。这行得通。

                              如果您将 Excel 工作表保存为 XML 文档,您还可以使用代码为 EXCEL 构建 XML 文件。我已经用 word 完成了这个,所以你不必使用第三方包。

                              这可以将 JTable 代码取出,然后只写一个标签分隔到任何文本文件,然后导入 Excel。我希望这会有所帮助。

                              代码:

                              import java.io.File;
                              import java.io.FileWriter;
                              import java.io.IOException;
                              import javax.swing.JTable;
                              import javax.swing.table.TableModel;
                              
                              public class excel {
                                  String columnNames[] = { "Column 1", "Column 2", "Column 3" };
                              
                                  // Create some data
                                  String dataValues[][] =
                                  {
                                      { "12", "234", "67" },
                                      { "-123", "43", "853" },
                                      { "93", "89.2", "109" },
                                      { "279", "9033", "3092" }
                                  };
                              
                                  JTable table;
                              
                                  excel() {
                                      table = new JTable( dataValues, columnNames );
                                  }
                              
                              
                                  public void toExcel(JTable table, File file){
                                      try{
                                          TableModel model = table.getModel();
                                          FileWriter excel = new FileWriter(file);
                              
                                          for(int i = 0; i < model.getColumnCount(); i++){
                                              excel.write(model.getColumnName(i) + "\t");
                                          }
                              
                                          excel.write("\n");
                              
                                          for(int i=0; i< model.getRowCount(); i++) {
                                              for(int j=0; j < model.getColumnCount(); j++) {
                                                  excel.write(model.getValueAt(i,j).toString()+"\t");
                                              }
                                              excel.write("\n");
                                          }
                              
                                          excel.close();
                              
                                      }catch(IOException e){ System.out.println(e); }
                                  }
                              
                                  public static void main(String[] o) {
                                      excel cv = new excel();
                                      cv.toExcel(cv.table,new File("C:\\Users\\itpr13266\\Desktop\\cs.tbv"));
                                  }
                              }
                              

                              【讨论】:

                              • (您只需将字符串数组存储在 JTable 中,然后取回字符串以写入制表符分隔的“CSV”文件。JTable 在此算法中是多余的......)
                              猜你喜欢
                              • 1970-01-01
                              • 1970-01-01
                              • 1970-01-01
                              • 2013-11-09
                              • 1970-01-01
                              • 1970-01-01
                              • 1970-01-01
                              • 1970-01-01
                              • 1970-01-01
                              相关资源
                              最近更新 更多