如何使用jxl库读取基于在Excel中输入的标签的数据

时间:2016-01-06 12:50:40

标签: selenium-webdriver jxl

我想从excel表中读取数据

我的情况是我在excel中有以下数据: | URL |状态| www1.com 1/6/2016 www2.com 1/6/2016 www3.com

我的情况是我想要获取未设置状态的url,还需要在状态字段中写入当前日期。

1 个答案:

答案 0 :(得分:0)

here is the working code:    

package projects;

    import java.io.File;
    import java.text.SimpleDateFormat;
    import java.util.Date;

    import jxl.Workbook;
    import jxl.biff.CellFinder;
    import jxl.write.Label;
    import jxl.write.WritableSheet;
    import jxl.write.WritableWorkbook;

    public class Test {

        public static void main(String[] args) 
        {
            try
            {
                System.out.println("Starting Program: ");

                File file = new File("/Users/Pankaj/Desktop/Test.xls");

                Workbook book = Workbook.getWorkbook(file);
                WritableWorkbook copiedBook = Workbook.createWorkbook(file, book);
                WritableSheet sheet = copiedBook.getSheet(0);

                CellFinder cellFind = new CellFinder(sheet);
                for(int row=1;row<sheet.getRows();row++)
                {
                    int urlColumn = cellFind.findLabelCell("URL").getColumn();
                    int statusColumn = cellFind.findLabelCell("Status").getColumn();

                    String urlNoStatus = sheet.getCell(urlColumn, row).getContents();
                    String noStatus = sheet.getCell(statusColumn, row).getContents();

                    if(noStatus.isEmpty())
                    {
                        System.out.println("URL WITHOUT STATUS: "+urlNoStatus);

                        Date date = new Date();
                        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
                        String formattedDate = sdf.format(date);

                        Label status = new Label(statusColumn, row, formattedDate);
                        sheet.addCell(status);
                    }
                }


                copiedBook.write();
                copiedBook.close();
                book.close();

                System.out.println("Ending Program: ");

            }catch(Exception e)
            {
                e.printStackTrace();
            }

        }

    }