[英]How do I use Java to read a .csv file and insert its data into SQL Server?
[英]How do I upload a CSV file and then automatically insert the data into the DB?
我有基于Java的Spring MVC应用程序,该应用程序也使用Spring安全性。 我正在使用休眠作为此Web应用程序的ORM工具。
以下是我的要求-
用户将能够使用网络浏览器上传CSV文件。 已知CSV文件的格式具有以下5个字段:
userId, location, itemId, quantity, tranDate 001, NY, 00A8D5, 2, 12/31/2012 002, MN, 00A7C1, 10, 12/22/2012 . .
这样大约有100行。
我在项目中使用Super CSV:
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";
如何达到此要求,以便使用Spring MVC通过网页上的按钮提供CSV文件路径位置?
是否还可以从远程位置自动拾取文件,以便我将文件上传到FTP位置,然后程序可以连接到远程ftp位置并按计划处理文件?
PS:我是文件操作的新手,如果有人可以指出某篇文章,那将很棒。
这样大约有100行。
不要费心将CSV保存为tmp文件,因为Spring的Mulitpart会为您做到这一点,并直接插入行( 请求可能需要更长的时间才能处理,但是鉴于您的表面知识,您可以稍后进行优化 )
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();
使您的控制器类似:
@RequestMapping(value = "/add", method=RequestMethod.POST)
public String upload(@RequestParam("file") MultipartFile file) throws IOException {
// call your csv parsing code.
}
确保您的表格看起来像:
<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的IO Decorator模式 。
我建议您将其保持尽可能简单,以便您可以学习基础知识。 然后担心添加更多可靠的解决方案/库。
您需要按照此处的说明创建FileUploadController。 然后,当您在servlet中将文件作为流获取时,您需要进行所有验证并将文件保存到临时/永久位置,以便以后在数据库导入过程中使用它。
为了使用远程FTP文件位置,我将研究Spring Integration。 有关此文档,请参见此处 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.