[英]How to read data from CSV and write it in HTML template using java
I want to read data from CSV file and write the data in html template using java. 我想从CSV文件中读取数据,并使用Java在html模板中写入数据。 right now I am reading csv file but while writing the data into html template, looping of data is not happening.
现在我正在读取csv文件,但是在将数据写入html模板时,没有发生数据循环。 (ie if there are 10 rows in csv file then it should create 10 rows dynamically in html table but that is not happening )
(即,如果csv文件中有10行,那么它应该在html表中动态创建10行,但是这没有发生)
I googled a lot but couldn't find any relevant examples. 我在Google上搜索了很多,但是找不到任何相关示例。 It would help me a lot if you share any POC or example.
如果您分享任何POC或示例,对我会有很大帮助。 Thanks in advance.
提前致谢。
Java code Java代码
import java.io.File;
import java.io.FileReader;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import com.opencsv.CSVReader;
@Controller
public class HelloController {
String totalScenarios ;
String passScenarios ;
@RequestMapping("/")
String home(ModelMap modal) throws Exception{
//reading from csv file
CSVReader reader = new CSVReader(new FileReader("employees.csv"));
List<String[]> myEnteries = reader.readAll();
reader.close();
for(String[] entry:myEnteries)
{
System.out.println(Arrays.toString(entry));
totalScenarios = Arrays.toString(entry);
passScenarios = entry.toString();
// writing in html file
modal.addAttribute("title", totalScenarios);
modal.addAttribute("message", passScenarios);
}
return "hello";
}
}
CSV data CSV数据
[1, java, java, 1]
[2, angular, angular, 1]
[3, java, java, 1]
HTML template HTML模板
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" type="text/css" href="css/bootstrap.css" />
</head>
<body>
<div class="container">
<div class="jumbotron">
<h2>${title}</h2>
<table>
<thead>
<tr>
<th>title</th>
</tr>
</thead>
<tbody>
<tr>
<td>${title}</td>
</tr>
<tr>
<td>${title}</td>
</tr>
</tbody>
</table>
</div>
</div>
Your modelMap will only have the last row from the csv file in it. 您的modelMap仅包含csv文件的最后一行。 It's a map, not a list, so model.addAttribute() will replace the previous value with the new value.
它是一个映射,而不是列表,因此model.addAttribute()将用新值替换之前的值。 Not sure what you need for your templating, but if a list of strings works you'd need to do something like...
不确定模板所需的内容,但是如果字符串列表有效,则需要执行以下操作:
List<String> totalScenarios = new ArrayList<>();
List<String> passScenarios = new ArrayList<>();
for(String[] entry:myEnteries)
{
totalScenarios.add(Arrays.toString(entry));
passScenarios.add(entry.toString());
}
// writing in html file
modal.addAttribute("title", totalScenarios);
modal.addAttribute("message", passScenarios);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.