如何在硒..的单个工作簿中创建多个工作表并为每个工作表提取数据

时间:2019-04-26 09:41:47

标签: java apache-poi

我想在一个工作簿中创建多个工作表。如何用硒编写代码

public static void main(String[] args) {

        List<String[]> value=null;
        Set<String> uniquename = new HashSet<String>();
        List<String[]> data1 = new  ArrayList<String[]>();
        data1.add( new String[] {"Apple iPhone 8 Plus (Space Grey, 64 GB)","56000"});
        data1.add(new String[] {"Apple iPhone 6 (Grey, 128 GB)","47000"});
        data1.add(new String[] {"Apple iPhone XS (Space Grey, 512 GB)","28000"});
        data1.add(new String[] {"Apple iPhone XS (Space Grey, 512 GB)","29000"});
        data1.add(new String[] {"Apple iPhone 7 Plus (Gold, 128 GB)","19000"});
        data1.add(new String[] {"Apple iPhone 7 Plus (Gold, 128 GB)","18000"});

        Map<String,List<String[]> > hashmap = new LinkedHashMap<String,List<String[]> >();

        for(String[] data:data1) {
public static  void write(String name, String pname, String pprice) {

         XSSFSheet sheet = workbook1.createSheet(name);
         Row row = sheet.createRow(1);
         Cell cell1 = row.createCell(0);
         Cell cell2 = row.createCell(1);

         cell1.setCellValue(pname);
         cell2.setCellValue(pprice);

    }


    public static void save(XSSFWorkbook workbook)
    {
        try
        {

            FileOutputStream out = new FileOutputStream("iphonedata_demo.xlsx");
            workbook.write(out);

            out.close();
            System.out.println("iphonedata_demo.xlsx written successfully on disk.");
        }catch (Exception e) {

        } 
    }


}

1 个答案:

答案 0 :(得分:0)

您必须为数组列表中的每个唯一名称创建一张表格...
以下代码重新排列了您在Map<String, List<String>>中提供的条目,以便将唯一的电话名称作为键,并将列表中的所有价格(取决于您的决定是否唯一)作为值。看一下代码注释:

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class Main {

    public static void main(String[] args) {
        List<String[]> data1 = new ArrayList<String[]>();
        data1.add(new String[] { "Apple iPhone 8 Plus (Space Grey, 64 GB)", "56000" });
        data1.add(new String[] { "Apple iPhone 6 (Grey, 128 GB)", "47000" });
        data1.add(new String[] { "Apple iPhone XS (Space Grey, 512 GB)", "28000" });
        data1.add(new String[] { "Apple iPhone XS (Space Grey, 512 GB)", "29000" });
        data1.add(new String[] { "Apple iPhone 7 Plus (Gold, 128 GB)", "19000" });
        data1.add(new String[] { "Apple iPhone 7 Plus (Gold, 128 GB)", "18000" });

        Map<String, List<String>> pricesPerPhoneName = new HashMap<String, List<String>>();

        /*
         * rearrange the given data in order to have unique names as keys and then use
         * those for sheet creation
         */
        data1.forEach(arr -> {
            String phoneName = arr[0];
            String price = arr[1];
            // check if the key is present in the map
            if (pricesPerPhoneName.containsKey(phoneName)) {
                /*
                 * add another price to the list of prices for the current key, check if the
                 * price is already contained and do nothing if yes...
                 */
                List<String> prices = pricesPerPhoneName.get(phoneName);
                if (!prices.contains(price)) {
                    prices.add(price);
                }
            } else {
                // put key and a list with the (one and only so far) price
                List<String> prices = new ArrayList<String>();
                prices.add(price);
                pricesPerPhoneName.put(phoneName, prices);
            }
        });

        /*
         * Now, you have all the prices stored as values of each key, which is a unique
         * phone name. The remaining code handles the creation of elements of the workbook
         */

        XSSFWorkbook workbook = new XSSFWorkbook();
        // provide a full path to the workbook
        Path workbookPath = Paths.get("C:\\iphones.xlsx");  // CHANGE TO YOUR PATH

        // creat a sheet for each phone name and write the data into it
        pricesPerPhoneName.forEach((name, prices) -> {
            /*
             * ########################################################################
             * ### please note that names for sheets in excel have a limited length ###
             * ### that's why the common prefix gets replaced by nothing here       ###
             * ########################################################################
             */
            XSSFSheet sheet = workbook.createSheet(name.replace("Apple iPhone", ""));

            // write one row for each price
            for (int i = 0; i < prices.size(); i++) {
                XSSFRow row = sheet.createRow(i);
                // write the phone name in column A and the price in column B
                XSSFCell phoneNameCell = row.createCell(0);
                XSSFCell phonePriceCell = row.createCell(1);
                phoneNameCell.setCellValue(name);
                phonePriceCell.setCellValue(prices.get(i));
            }

            // make the columns fit their content
            sheet.autoSizeColumn(0);
            sheet.autoSizeColumn(1);
        });

        // write the workbook via FileOutputStream
        try (FileOutputStream fos = new FileOutputStream(workbookPath.toAbsolutePath().toString())) {
            // write the workbook using the FileOutputStream
            workbook.write(fos);
            // force the FileOutputStream to write everything until it is empty
            fos.flush();
            // close the FileOutputStream
            fos.close();
            // close the workbook.
            workbook.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

可以设置单元格的格式,例如告诉Excel对价格单元格使用某些货币格式,但这取决于您...基本上是另一个问题;-)