首页 > 解决方案 > 如何使用java在html表中创建行

问题描述

我必须将 cvs 文件中的值导出到数组中,然后将其导出到 html 表中。

我尝试了经典的 for 循环,但这使得代码不起作用

    String csvFile = "/Users/baab/baab/baab/data.csv";
    BufferedReader br = null;
    String line = "";
    String cvsSplitBy = ",";

    try {

        br = new BufferedReader(new FileReader(csvFile));
        while ((line = br.readLine()) != null) {


            String[] country = line.split(cvsSplitBy);
            String Krajina = country[0]+" ";
            String Rok = country[1];
            String Vendor = country[2];
            String Units = country[3];
            String KrajinaArray[] = Krajina.split(",");
            String RokArray[] = Rok.split(",");
            String VendorArray1[] = Vendor.split(",");
            String UnitsArray1[] = Units.split(",");

            for(int d=0; d < UnitsArray1.length; d++){
            for(int c=0; c < VendorArray1.length; c++){
            for(int b=0; b < RokArray.length; b++){
            for(int i=0; i < KrajinaArray.length; i++){


            //System.out.println("Krajina: "+ country[0]+", Rok: "+ country[1]+", Vendor: "+country[2]+", Units: "+country[3]);
                File f = new File("/Users/baab/baab/baab/data.csv"");
                PrintWriter pw = new PrintWriter(f);
             String html= "<style> table, th, td { border: 1px solid black; </style> </head> <body> <table> <tr> <th>Cc</th> <th>Timescale</th> <th>Vendor</th> <th>Units</th> </tr> <tr> <td>"+KrajinaArray[i]+"</td> <td>"+RokArray[b]+"<td>"+VendorArray1[i]+"<td>"+UnitsArray1[b]+"</td> </table>";

            try {
                BufferedWriter bw = new BufferedWriter(new FileWriter(f));
                bw.write(html);
                bw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

我想用所有值在表中创建行..

标签: javahtmlcsv

解决方案


这应该可以解决您的需求。由于您已经有了输出一行的代码,因此只需在删除其他 html 元素之后添加循环即可。

它可能看起来像这样:

List<String> list = new ArrayList<String>();

String documentPre = "<html><style> table, th, td { border: 1px solid black; </style> </head> <body>";
list.add(documentPre);

String headerColumn = "<table> <tr> <th>Cc</th> <th>Timescale</th> <th>Vendor</th> <th>Units</th> </tr>";
list.add(headerColumn);

<a loop over a single csv entry>

String htmlColumn = "<tr> <td>"+KrajinaArray[i]+"</td> <td>"+RokArray[b]+"<td>"+VendorArray1[i]+"<td>"+UnitsArray1[b]+"</td>";
list.add(htmlColumn);

<your loop's end>

String documentPost = " </table></body></html>";
list.add(documentPost );

try (BufferedWriter bw = new BufferedWriter(new FileWriter(f))) {

    for (String html : list) {
        bw.write(html);
    }

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

注意:我添加了一些缺少的标签,但我没有修复样式部分。你只需要添加你剪下的部分。

注2:我用try-with-resource替换了写作部分,所以关闭操作总是自动发生。阅读它。

注意 3:您介意正确格式化您的 html 输出,使其更易于阅读。

注意 4:假设您的 csv 行之一包含元素(krajina、rok、vendor、units),您的循环应该替换为在单个 csv 上循环的内容。然后将其拆分并将值传递到相关列中。

我怀疑您代码中的这四个复杂循环是否正确。


推荐阅读