簡體   English   中英

如何讀寫excel文件

[英]How to read and write excel file

我想從 Java 讀取和寫入一個 3 列 N 行的 Excel 文件,在每個單元格中打印一個字符串。 誰能給我簡單的代碼片段? 我需要使用任何外部庫還是 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]

試試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 文件的示例。

Apache POI可以為您做到這一點。 特別是HSSF模塊。 快速指南最有用。 以下是如何做你想做的 - 特別是創建一個工作表並將其寫出來。

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();

首先在您的項目類路徑中添加所有這些 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();
    }
}

你也可以考慮JExcelApi 我發現它的設計比 POI 更好。 有一個教程在這里

有一個新的簡單且非常酷的工具(Kfir 的 10 倍): 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();

要讀取 xlsx 文件,我們可以使用Apache POI庫試試這個:

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();
        }

    }

.csv 或 POI 肯定會這樣做,但您應該知道 Andy Khan 的JExcel 我認為它是迄今為止最好的用於處理 Excel 的 Java 庫。

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();
    }

並確保已將 jars poi 和 poi-ooxml (org.apache.poi) 添加到您的項目中

一個簡單的 CSV 文件就足夠了

為了從 .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

當然,您會發現下面的代碼很有用且易於閱讀和編寫。 這是一個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);

    }

}

}

使用 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();
                }
            }

我編輯了投票最多的一個,因為它沒有完全計算空白列或行,所以這是我測試過的代碼,現在可以在 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();}

如果列號可變,您可以使用它

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();
    }
}

相應的mavendependency可以在這里找到

另一種讀取/寫入 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"));

您需要 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();
    }

請使用 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();
    }
   }
}

您不能並行讀寫同一個文件(讀寫鎖)。 但是,我們可以對臨時數據(即輸入/輸出流)進行並行操作。 只有在關閉輸入流后才將數據寫入文件。 應遵循以下步驟。

  • 打開文件到輸入流
  • 將同一個文件打開到輸出流
  • 讀取並進行處理
  • 將內容寫入輸出流。
  • 關閉讀/輸入流,關閉文件
  • 關閉輸出流,關閉文件。

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();
        }
    }
}

使用 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();
        }

如果您選擇第三方庫選項,請嘗試使用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.
}

希望這個對你有幫助。

附注。 我在 Aspose 擔任支持開發人員/布道者。

如果您需要對 Java 中的 Office 文檔執行更多操作,請選擇前面提到的 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();
 }
}

這會將 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"));
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM