csv导入文件会把每列的数据用英文逗号分割开来,如果遇到某列中包含英文逗号,则会把该列用英文双引号进行包装。

如果csv文件中某列的数据本身包含英文逗号,应该使用读取字符串的方式进行解析数据,如csv的数据如下,ReGoodsCode,SKUCode,PlatformCode,GoodsName,GoodsCount,RefundAmount,Phone,MallID,UserName,ReTime
1.56E+14,xg003809216-z,4M天猫旗舰店,"4M ,,高曼",5,500,13907927272,"匿名用户,lisi","张三,xxx,ooo",2014/12/23 14:10

这时应用如下方法进行解析数据,

private IEnumerable<string[]> ExCsv1(string path)
        {
            var sr = File.ReadAllLines(path, System.Text.Encoding.UTF8);
            int i = 0, m = 0;

for (var a = 1; a < sr.Length; a++)
            {
                string[] split = sr[a].Split(',');
                string[] newsplit = new string[split.Length];
                var fix = 0;

for (i = 0; i + fix < split.Length; i++)
                {
                    newsplit[i] = split[i + fix];
                    if (newsplit[i].StartsWith("\"") && !newsplit[i].EndsWith("\""))
                    {
                        for (var j = i + fix + 1; j < split.Length; j++, fix++)
                        {
                            newsplit[i] += "," + split[j];
                            if (split[j].EndsWith("\"")) break;
                        }
                    }
                }
                yield return newsplit;
            }
        }

使用时,

if (FileUpload1.HasFile)
            {
                try
                {
                    //FileUpload1.SaveAs(Server.MapPath("upload") + "\\" + FileUpload1.FileName);
                    //这里永远只保存一个文件
                    string path = ConfigurationManager.AppSettings["ReturnGoodsPath"];
                    FileUpload1.SaveAs(path + FileUpload1.FileName);
                    var dt = ExCsv1(path + FileUpload1.FileName);
                    //DataTable dt = csv2dt(path + FileUpload1.FileName, 1);
                    //var codeisInt = dt.Columns[0].DataType == typeof(int) || dt.Columns[0].DataType == typeof(double);

//绑定数据源
                    //GridView1.DataSource = dt;
                    //GridView1.DataBind();

var msg = "客户端路径:" + FileUpload1.PostedFile.FileName + "<br>" +
                    "文件名:" + System.IO.Path.GetFileName(FileUpload1.FileName) + "<br>" +
                    "文件扩展名:" + System.IO.Path.GetExtension(FileUpload1.FileName) + "<br>" +
                    "文件大小:" + FileUpload1.PostedFile.ContentLength + " KB<br>" +
                    "文件MIME类型:" + FileUpload1.PostedFile.ContentType + "<br>" +
                    "保存路径:" + Server.MapPath("upload") + "\\" + FileUpload1.FileName;

List<ReOrder> r = new List<ReOrder>();
                    foreach (var item in dt)
                    {
                        string orderCode = item[0].ToString();// codeisInt ? ((double)item[0]).ToString("D") : item[0].ToString();
                        string productCode = item[1].ToString();
                        ReOrder ord = r.Where(t => t.Code == orderCode).FirstOrDefault();

if (ord == null)
                        {
                            ord = new ReOrder();
                            ReOrderDetail det = new ReOrderDetail();

ord.Code = orderCode;// item[0].ToString();
                            det.SKUCODE = item[1].ToString();
                            ord.PlatformCode = item[2].ToString();
                            det.GoodsName = item[3].ToString();
                            det.GoodsCount = int.Parse(item[4].ToString());
                            ord.TotalAmount = decimal.Parse(item[5].ToString());
                            det.TotalAmount = decimal.Parse(item[5].ToString());
                            ord.phone = item[6].ToString();
                            ord.MallID = item[7].ToString();
                            ord.UserName = item[8].ToString();
                            ord.ReGoodsTime = DateTime.Parse(item[9].ToString());
                            ord.ReOrderDetails.Add(det);
                            r.Add(ord);
                        }
                        else if (!ord.ReOrderDetails.Any(d => d.SKUCODE == productCode))
                        {
                            ReOrderDetail det = new ReOrderDetail();
                            det.SKUCODE = item[1].ToString();
                            det.GoodsName = item[3].ToString();
                            det.GoodsCount = int.Parse(item[4].ToString());
                            det.TotalAmount = decimal.Parse(item[5].ToString());
                            ord.TotalAmount = ord.TotalAmount + decimal.Parse(item[5].ToString());
                            ord.ReOrderDetails.Add(det);
                        }
                    }

var returnGoodsGroups = r.GroupBy(x => x.phone).ToArray();

foreach (var item in returnGoodsGroups)
                    {

LogEntry entry = new LogEntry("返回退货", 1);
                        LogStub.Log(entry);
                        var res = await LogicStub.ReturnGoodsHandler.HandleReturnGoods(new SDK.ReturnGoodsInfo
                           {
                               Orders = item.ToList(),
                               MemberKeyValue = item.Key
                           });
                        msg += "<br/>" + res;// == "{}" ? "<br/>OK!" : "<br/>" + res;

}
                    Label1.Text = msg;
                }
                catch (Exception ex)
                {
                    Label1.Text = "发生错误:" + ex.Message.ToString();
                }
            }

也可以使用以下方法获取数据,但此方法可能无法解决列数据中包含英文逗号的问题:

/// <summary>
        /// CSV文件转换
        /// 作为数据源
        /// </summary>
        /// <returns></returns>
        private DataTable ExCsv(string path)
        {
            // csv file:HDR=Yes-- first line is header
            string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path
                + ";Extended Properties='TEXT;HDR=Yes;FMT=Delimited;CharacterSet=65001;'";
            OleDbConnection oleConn = new OleDbConnection(strConn);
            oleConn.Open();
            DataTable sheets = oleConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
            DataTable dt = new DataTable();
            if (sheets != null && sheets.Rows.Count > 0)
            {
                String fileName = sheets.Rows[0]["TABLE_NAME"].ToString(); // sheets.Rows[0] -- first sheet of excel 
                string olestr = "select * from [" + fileName + "]";
                OleDbCommand oleComm = new OleDbCommand(olestr, oleConn);
                oleComm.Connection = oleConn;
                OleDbDataAdapter oleDa = new OleDbDataAdapter();
                oleDa.SelectCommand = oleComm;
                oleDa.Fill(dt);
                oleConn.Close();
            }
            return dt;
        }

调用时,

if (FileUpload1.HasFile)
            {
                    //FileUpload1.SaveAs(Server.MapPath("upload") + "\\" + FileUpload1.FileName);
                    //这里永远只保存一个文件
                    string path = ConfigurationManager.AppSettings["ReturnGoodsPath"];
                    FileUpload1.SaveAs(path + FileUpload1.FileName);
                    DataTable dt = ExCsv(path);

//绑定数据源
                    //GridView1.DataSource = dt;
                    //GridView1.DataBind();

Label1.Text = "客户端路径:" + FileUpload1.PostedFile.FileName + "<br>" +
                    "文件名:" + System.IO.Path.GetFileName(FileUpload1.FileName) + "<br>" +
                    "文件扩展名:" + System.IO.Path.GetExtension(FileUpload1.FileName) + "<br>" +
                    "文件大小:" + FileUpload1.PostedFile.ContentLength + " KB<br>" +
                    "文件MIME类型:" + FileUpload1.PostedFile.ContentType + "<br>" +
                    "保存路径:" + Server.MapPath("upload") + "\\" + FileUpload1.FileName;

}

读取上传的CSV为DataTable的更多相关文章

  1. Springboot/SpringMvc 读取上传 xls 文件内容

    /** * 读取上传 xls 内容返回 * @param file * @return */@RequestMapping(value = "/read.xls")@Respons ...

  2. File API 读取上传的文件

    1, 在html 文档中,<input type="file"> 我们可以选择文件进行上传,但这时只能上传一个文件.如果加上multiple 属性,可以上传多个文件,上 ...

  3. HTML5 读取上传文件(转载)

    另参考 http://www.jianshu.com/p/46e6e03a0d53 1 filelist对象与file对象: <input type="file" id=&q ...

  4. ci框架读取上传的excel文件数据

    原文链接: https://blog.csdn.net/qq_38148394/article/details/87921373 此功能实现使用到PHPExcel类库,PHPExcel是一个PHP类库 ...

  5. 上传文件csv 导入功能

    HTML代码: <script> function uploadCsv() { $('#chooseCsvFile').click(); } function doUploadCsv() ...

  6. webapi读取上传的文件流

    逻辑说明 这里未引用System.Web.Mvc. 主要使用MultipartMemoryStreamProvider对象从Request中获取文件流. var provider = new Mult ...

  7. .NET 上传并解析CSV文件存库

    1.前端: 放置浏览按钮 <div class="row inner_table text-center"> <input id="fileId&quo ...

  8. php上传excle文件,csv文件解析为二维数组

    解析上传的CSV文件不是什么难事,直接读取转成你想要的数组样子就OK了. public function putStoreStockIn ($filePath = '') { $file = fope ...

  9. web操作文件的上传到服务器 并可下载 并且读取出来

    1.文件的上传-servlet实现文件上传---核心API—DiskFileItemFactory 一.文件上传概述 l  实现web开发中的文件上传功能,需完成如下二步操作: •    在web页面 ...

随机推荐

  1. iOS开发小技巧--图片的圆角处理

    图片圆角处理方案一: 缺点是图片多了感觉卡 设置图层的CornerRadius属性 -- 设置了圆角后,运行程序没有反应,多半是没有设置下面这句:让内容遵循设置的边缘 masksToBounds = ...

  2. Lazy Acquisition

    为什么要延迟? 延迟加载模式是用于快速启动.保证初始化时不必浪费时间去加载和运算,而在需要的时候再去调用. 框架中有实现吗? .NET典型的使用在4.0中已经有了,Lazy<T> 特性:线 ...

  3. android数据存储之SharedPreferences

    一.SharedPreferences简介      (1)SharedPreferences是Android平台上一个轻量级的存储类,用来保存应用的一些常用配置,比如Activity状态,Activ ...

  4. JavaScript 将多个引用(样式或者脚本)放入一个文件进行引用

    1.将样式放入一个文件进行引用 @import url("../media/css/bootstrap.min.css"); @import url("../media/ ...

  5. 如何让PHP支持Redis

    原理:php默认扩展库不含有redis扩展:要支持redis扩展,需要有redis.so这个扩展文件 所以我们的目标就是生成redis.so扩展文件,并修改php.ini 让其支持redis扩展. 准 ...

  6. 利用jackson转成json字符串(ssh中)

    public String getJsonString(Object o){ ObjectMapper om = new ObjectMapper(); StringWriter sw = new S ...

  7. 如何查看sql server端口号

    通过sql server配置管理器-->sql server网络配置-->选择-->通过右侧选择TCP/IP(已启用)-->查看属性 还可以通过sql语句查看: exec sy ...

  8. 单片机C语言基础编程源码六则

    1.某单片机系统的P2口接一数模转换器DAC0832输出模拟量,现在要求从DAC0832输出连续的三角波,实现的方法是从P2口连续输出按照三角波变化的数值,从0开始逐渐增大,到某一最大值后逐渐减小,直 ...

  9. No compiler is provided in this environment. --Maven build失败

    今天,maven build 失败了, 遇到下面的问题 经过查找,通过这个大佬的blog(  https://blog.csdn.net/lslk9898/article/details/738367 ...

  10. Linux服务器上搭建web项目环境

    一.下载并安装jdk 去官网下载linux系统上jdk的安装包jdk-8u181-linux-x64.tar.gz,在Linux的/usr目录下新建文件夹java,可以使用命令:cd /usr    ...