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. .net网站的文件上传读取进度条和断点下载

    文件上传到服务器时的进度读取 //调整上传配置 AdapterInfo(info); UpfileResult result = new UpfileResult(); try { //直接使用req ...

随机推荐

  1. 使用python+django+twistd 开发自己的操作和维护系统的一个

    许多开源操作系统和维护系统,例nagios.zabbix.cati等等,但是,当他们得到的时间自己的个性化操作和维护需求,始终无力! 最近的一项研究python.因此,我们认为python+djang ...

  2. javascript有用小技巧—实现分栏显示

    记得给师哥师姐測试考试系统的时候,看到他们的考试页面能够实现隐藏左边的考生信息部分,当时认为好高大上.好人性化. 如今学了javascript,我也能实现这个功能了,以下来显摆一下. 1.页面设计: ...

  3. php 两个文件之间的相对路径的计算方法

    php 两个文件之间的相对路径的计算方法 比如: 文件A 的路径是 /home/web/lib/img/cache.php 文件B的路径是 /home/web/api/img/show.php 那么. ...

  4. JavaFX它ListView使用

    ListView它是通过同一控制非.在JavaFX在.ListView此外,它拥有非常丰富的功能.下列.让我们来看看如何使用ListView. ListView位于javafx.scene.contr ...

  5. Oracle游标(光标)

     watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvdGFuZ2xpdXFpbmc=/font/5a6L5L2T/fontsize/400/fill/I0J ...

  6. Memcached全面剖析–5. memcached的应用和兼容程序

    作者:长野雅广(Masahiro Nagano)  原文链接:http://gihyo.jp/dev/feature/01/memcached/0005 我是Mixi的长野.memcached的连载最 ...

  7. 同ListView该接口无法通过手势滑动左右切换界面问题解决方法

    同ListView该接口无法通过手势滑动左右切换界面问题解决方法 问题描写叙述: 在做OnGestureListener滑动切换窗体的时候,会遇到这种问题.就是当界面中含有ListView的时候.On ...

  8. ECharts SSH+JQueryAjax+Json+JSP在数据库中的数据来填充ECharts在

    1导入包.设定SSH框架. 进口JQuery的JS包.<script src="JS/jquery-1.7.1.js"></script> 导入EChart ...

  9. c# 用正则表达式在指定的字符串中每隔指定个数的文字插入指定字符串

    public static string AddNewLine(string inString,int num,string addString="\r\n") { return ...

  10. JGroups 入门实践(转)

    前言 JGroups是一个开源的纯java编写的可靠的群组通讯工具.其工作模式基于IP多播,但可以在可靠性和群组成员管理上进行扩展.其结构上设计灵活,提供了一种灵活兼容多种协议的协议栈. JGroup ...