【问题标题】:Store multiple values in excel based on search criteria根据搜索条件在excel中存储多个值
【发布时间】:2019-06-22 11:16:45
【问题描述】:

我通过查询从数据库中获取 emp id,并将 emp id 存储在 excel 表中。例如,将 10 个 emp id 存储在名为 empid 详细信息的 excel 中。从excel中获取一个emp id并在应用程序中搜索后,我们得到员工发票编号列表,需要将这些发票编号列表存储在第一列中,并将相关emp id存储在另一个名为发票详细信息的excel中的第二列中。只有首先我们需要存储在 excel 中的 10 个发票号码列表。 我已经完成了用于存储单个 emp Id 发票详细信息的编码部分。任何人都可以帮助我如何实现 n Num of emp Id 的代码并使用 emp id 存储他们的发票。

提前致谢。

【问题讨论】:

  • 分享更多信息,例如您到目前为止编码的内容以及您发现一些图片或代码的困难之处
  • 正如您所提到的,您已经完成了存储单个(第一个)emp Id 发票详细信息的编码 - 就像以同样的方式,尝试通过增加行索引来循环最多 n 次。
  • 我可以将发票编号放入循环中以存储所有 emp id。但我的问题是如何将带有发票编号的 emp Id 存储在发票编号 Excel 表中。
  • 贴出你试过的代码和结果。

标签: java selenium selenium-webdriver cucumber-java


【解决方案1】:

根据您的要求替换 Excel 文件名、工作表名称、行号、列号和存储值,并按照 cmets 进行说明。

试试下面的代码:

import java.io.File;
import java.util.List;

import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;

public class Answer {
    // Below method will give the excel data based on the passed row and the column number
    private static String getData(String fileName, String sheetName, int rowNumber, int columnNumber) throws Exception {
        Workbook workbook = WorkbookFactory.create(new File(fileName));
        Sheet sheet = workbook.getSheet(sheetName);
        Row row = sheet.getRow(rowNumber);
        return row.getCell(columnNumber).getStringCellValue().trim();
    }
    // Below method will return the row count
    private static int getRowCount(String fileName, String sheetName) throws Exception {
        return WorkbookFactory.create(new File(fileName)).getSheet(sheetName).getLastRowNum() + 1;
    }
    // Below method will store the data in excel sheet based on the passed row and column indexes
    private static void putData(String fileName, String sheetName, int rowNumber, int columnNumber, String cellValue) throws Exception {
        Workbook workbook = WorkbookFactory.create(new File(fileName));
        Sheet sheet = workbook.createSheet(sheetName);
        Row row = sheet.createRow(rowNumber);
        row.createCell(columnNumber).setCellValue(cellValue);
    }
    public static void main(String ...ali) throws Exception {
        // Retrieve data from the Database using some queries

        // Store the retrieved data into some excel sheet

        // After doing the above two steps, below code will retrieve previously stored emp id's and will store into an other excel sheet
        // Pass the corresponding absolute excel file path with name, sheet names in the below sample code 

        for(int i=0;i<getRowCount("SomeExcelFileName", "SomeExcelSheetName");i++) {
            // Get one by one emp id from excel
            String empID = getData("SomeExcelFileName", "SomeExcelSheetName", i, 0);

            // Search in the application and get invoice numbers list and store it
            List<String> invoiceDetails = null;

            // Store the invoice details list in the first column, here the row number is starting from 1 and column index is 0
            putData("AntoherExcelFile", "AnotherExcelSheet", (i+1), 0, invoiceDetails.toString());

            // Store the related emp id in the second column, here the row number is starting from 1 and column index is 1
            putData("AntoherExcelFile", "AnotherExcelSheet", (i+1), 1, empID);
        }
    }
}

如果程序成功执行且没有任何错误,那么您将在 excel 中获得以下示例格式的数据:

|Invoice Details | Emp ID|
| details 1      | 3333  |
| some details   | 1306  |
| Hello World!   | 2019  |

希望对你有帮助……

【讨论】:

  • 感谢您的回复。
  • 我的要求是完全不同的。我不能使用 Row 创建行。它是 jxl。
  • 好的,您正在使用名为JavaExcelAPI 的第三方库来获取数据。但是JXL只支持.xls文件格式,不能处理大数据量,推荐你使用Apache POI,因为它支持的多且好用。
  • 你是说我的代码也错了吗?因为您正在使用其他一些工具并且通过 apache poi 您没有满足您的要求?如果代码正确或要求正确,但您只想使用 jxl,那么我也可以尝试...
  • 我并不是说你的代码是错误的。我不能在我的代码中应用它。下面是我的代码。请帮助我如何存储所有emp id的前10个发票号码? public void connectToDatabaseAndGetData() 抛出异常{ Connection con = null; //这里提供驱动类 Class.forName("驱动名称").newInstance(); //提供db url, un,pwd con = DriverManager.getConnection("URL", "UN", "PWD"); System.out.println("已建立连接");结果集 rs = null; try{ 语句 stmt = con.createStatement(); System.out.println("语句创建");
【解决方案2】:

根据您的要求,我将代码从 Apache POI 更改为 Java Excel API,用于从 excel 中检索和存储数据。

试试下面的代码,如果您遇到任何问题,请告诉我...

import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import jxl.Cell;
import jxl.CellType;
import jxl.CellView;
import jxl.Sheet;
import jxl.Workbook;
import jxl.WorkbookSettings;
import jxl.format.UnderlineStyle;
import jxl.read.biff.BiffException;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

public class OneMore {
    private WritableCellFormat timesBoldUnderline;
    private WritableCellFormat times;
    private WritableWorkbook workbook;
    private WritableSheet excelSheet;
    private String inputFile;
    private List<String> empIDs, invoiceDetails;

    public void setOutputFile(String inputFile) {
        this.inputFile = inputFile;
    }

    public void write(int SheetNumber) throws Exception {
        File file = new File(inputFile);
        WorkbookSettings wbSettings = new WorkbookSettings();

        wbSettings.setLocale(new Locale("en", "EN"));

        workbook = Workbook.createWorkbook(file, wbSettings);
        workbook.createSheet("Required", SheetNumber);
        excelSheet = workbook.getSheet(SheetNumber);
        createLabel(excelSheet);
    }

    private void createLabel(WritableSheet sheet) throws Exception {
        // Lets create a times font
        WritableFont times10pt = new WritableFont(WritableFont.TIMES, 10);
        // Define the cell format
        times = new WritableCellFormat(times10pt);
        // Lets automatically wrap the cells
        times.setWrap(true);

        // create create a bold font with unterlines
        WritableFont times10ptBoldUnderline = new WritableFont(WritableFont.TIMES, 10, WritableFont.BOLD, false, UnderlineStyle.SINGLE);
        timesBoldUnderline = new WritableCellFormat(times10ptBoldUnderline);
        // Lets automatically wrap the cells
        timesBoldUnderline.setWrap(true);

        CellView cv = new CellView();
        cv.setFormat(times);
        cv.setFormat(timesBoldUnderline);
        cv.setAutosize(true);

        // Write a few headers
        addCaption(sheet, 0, 0, "Invoice Details");
        addCaption(sheet, 1, 0, "Emp ID");
    }

    private void retrieveDataFromDBAndStoreItInExcel(WritableSheet sheet) throws Exception {
        // Handling data base part
        Connection con = null;
        Class.forName("driver name").newInstance();
        con = DriverManager.getConnection("URL", "UN", "PWD");
        System.out.println("Connection Created");
        ResultSet rs = null;
        try{
            Statement stmt = con.createStatement();
            System.out.println("Statement Created");
            String query = "query to get data from db";
            rs = stmt.executeQuery(query);
            System.out.println("Query executed");
            ResultSetMetaData metadata = rs.getMetaData();
        }catch (Exception e) {
            System.out.println("Error.......: "+e);
        }

        // Storing the database data into the excel
        for(int i=0; rs.next();i++) {
            // First column
            addLabel(sheet, 0, i, rs.getString(1));
        }
        rs.close();
    }

    private void createContent(List<String> list, WritableSheet sheet, int columnNumber) throws Exception {
        for(int i=0; i<list.size();i++) {
            // First column
            addLabel(sheet, columnNumber, i, list.get(i).toString());
        }
    }

    private void addCaption(WritableSheet sheet, int column, int row, String s) throws Exception {
        Label label;
        label = new Label(column, row, s, timesBoldUnderline);
        sheet.addCell(label);
    }

    private void addLabel(WritableSheet sheet, int column, int row, String s) throws Exception {
        Label label;
        label = new Label(column, row, s, times);
        sheet.addCell(label);
    }

    public void read() throws Exception  {
        File inputWorkbook = new File(inputFile);
        empIDs = new ArrayList<String>();
        Workbook w;
        try {
            w = Workbook.getWorkbook(inputWorkbook);
            // Get the first sheet
            Sheet sheet = w.getSheet(0);
            // Loop over first column up to 10 rows
            for(int i=0;i<sheet.getRows();i++) {
                Cell cell = sheet.getCell(0, i);
                CellType type = cell.getType();
                if (type == CellType.LABEL) {
                    empIDs.add(cell.getContents());
                }
            }
        } catch (BiffException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws Exception {
        OneMore test = new OneMore();
        // Retrieving Data from the Database and storing in the First Excel
        test.setOutputFile("C:\\NotBackedUp\\OxygenWorkspace\\HelloSelenium\\src\\main\\resources\\test\\FirstExcel.xls");
        test.write(0);
        test.retrieveDataFromDBAndStoreItInExcel(test.excelSheet);
        test.workbook.write();
        test.workbook.close();
        System.out.println("=> The First Excel Writing task completed...");

        // Reading data from the First Excel and storing it in empIDs ArrayList
        test.read();
        System.out.println("=> The Excel Data is : "+test.empIDs);

        // You use empIDs ArrayList which has emp ids for getting the invoice details from the Application and store it in the invoiceDetails ArrayList below
        test.invoiceDetails = new ArrayList<String>();
        test.invoiceDetails.add("Invoice Details from the Application");

        // Writing the Invoice Details and the emp id Data to the Second Excel
        test.setOutputFile("C:\\NotBackedUp\\OxygenWorkspace\\HelloSelenium\\src\\main\\resources\\test\\SecondExcel.xls");
        test.write(0);
        test.createContent(test.invoiceDetails, test.excelSheet, 0);
        test.createContent(test.empIDs, test.excelSheet, 1);
        test.workbook.write();
        test.workbook.close();
    }
}

我第一次尝试使用 jxl,所以我测试了在我的系统中读取和写入数据到 excel 并按预期工作。

但是我还没有测试数据库部分和全部,所以尝试通过在 main() 方法中的 cmets 来修改/执行。您无需编写任何代码,只需根据您的要求更改一些配置细节和 excel 文件名路径即可。

希望对您有所帮助...快乐编码...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-11-11
    • 2014-10-24
    • 1970-01-01
    • 2016-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多