簡體   English   中英

根據搜索條件在excel中存儲多個值

[英]Store multiple values in excel based on search criteria

我通過查詢從數據庫中獲取 emp id 並將 emp id 存儲在 excel 表中。例如,在名為 empid details 的 excel 中存儲 10 個 emp id。 在從 excel 中逐個獲取 emp id 並在應用程序中搜索后,我們得到員工發票編號列表,需要將這些發票編號列表存儲在第一列中,並將相關的 emp Id 存儲在另一個名為發票詳細信息的 excel 中的第二列中。我們需要在 excel 中存儲的 10 個發票編號列表。 我已經完成了用於存儲單個 emp Id 發票詳細信息的編碼部分。 任何人都可以幫助我如何實現 n Num of emp Id 的代碼並使用 emp id 存儲他們的發票。

提前致謝。

根據您的要求替換 Excel 文件名、工作表名稱、行號、列號和存儲值,並按照注釋進行解釋。

試試下面的代碼:

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  |

我希望它有幫助...

根據您的要求,我將代碼從 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() 方法中的注釋修改/執行。 您不需要編寫任何代碼,只需要根據您的要求更改一些配置詳細信息和 excel 文件名路徑。

我希望它有幫助...快樂編碼...

暫無
暫無

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

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