gpt4 book ai didi

java - 如何上传 CSV 文件,然后自动将数据插入数据库?

转载 作者:搜寻专家 更新时间:2023-11-01 02:12:50 25 4
gpt4 key购买 nike

我有一个基于 Java 的 Spring MVC 应用程序,它也使用 Spring 安全性。我正在使用 hibernate 作为此 Web 应用程序的 ORM 工具。

以下是我的要求——

用户将能够使用网络浏览器上传 CSV 文件。已知 CSV 文件的格式具有以下 5 个字段:

userId, location, itemId, quantity, tranDate001, NY, 00A8D5, 2, 12/31/2012002, MN, 00A7C1, 10, 12/22/2012..

like this there are about 100 rows.

I am using Super CSV in the project:

private void readWithCsvBeanReader(String CSV_FILENAME) throws Exception {

String CSV_FILENAME = "\\\\Serv01\\Files\\QueryResult.csv";
//String CSV_FILENAME = "C:\\Files\\QueryResult.csv";
ICsvBeanReader beanReader = null;
try {
beanReader = new CsvBeanReader(new FileReader(CSV_FILENAME),
CsvPreference.STANDARD_PREFERENCE);

// the header elements are used to map the values to the bean (names
// must match)
final String[] header = beanReader.getHeader(true);
// get Cell Processor
final CellProcessor[] processors = getProcessors();

我在这里读取 CSV 文件的内容,然后使用 Hibernate,我正在插入它。

这很好用,因为我在本地或 Windows 共享上提供 CSV 路径。

String CSV_FILENAME = "\\\\Serv01\\Files\\QueryResult.csv";
or via this:
String CSV_FILENAME = "C:\\Files\\QueryResult.csv";
  1. 如何实现这一要求,以便使用 Spring MVC 的网页上的按钮提供 CSV 文件路径位置?

  2. 是否也可以从远程位置自动获取文件,以便我将文件上传到 FTP 位置,然后程序可以连接到远程 ftp 位置并按计划处理文件?

PS:我是文件操作的新手,如果有人能指出一些文章,那就太好了。

最佳答案

like this there are about 100 rows.

不要像 Spring 的 Mulitpart 那样费心将 CSV 保存为 tmp 文件会为你做的并直接插入行(请求可能需要更长的时间来处理,但鉴于您表面上的当前知识,您可以担心稍后优化它)

private void readWithCsvBeanReader(MultipartFile uploadedFile) throws Exception {

ICsvBeanReader beanReader = null;
try {
beanReader = new CsvBeanReader(new InputStreamReader(uploadedFile.getInputStream()),
CsvPreference.STANDARD_PREFERENCE);

// the header elements are used to map the values to the bean (names
// must match)
final String[] header = beanReader.getHeader(true);
// get Cell Processor
final CellProcessor[] processors = getProcessors();

让你的 Controller 像这样:

@RequestMapping(value = "/add", method=RequestMethod.POST)
public String upload(@RequestParam("file") MultipartFile file) throws IOException {
// call your csv parsing code.
}

确保你的 FORM 看起来像这样:

<h1>Add a File for testing</h1>
<form method="post" action="/add" class="well form-vertical" enctype="multipart/form-data">
<input type="file" name="file" />
<button type="submit" class="btn">{{actionLabel}}</button>
</form>

注意enctype

对于输入和输出你应该明白Java's IO Decorator pattern .

我建议您尽可能保持简单,以便您可以学习基础知识。然后考虑添加更强大的解决方案/库。

关于java - 如何上传 CSV 文件,然后自动将数据插入数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14107788/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com