导入代码,从csv文件得到datatable         /// <summary>
        /// Get Data From Csv File 
        /// (Through StreamReader)
        /// </summary>
        /// <returns></returns>
        private bool GetData(Stream inputStream, out string errMessage, out DataTable dtFile)
        {
            errMessage = String.Empty;
            dtFile = new DataTable();

//this.FileUploadImport.PostedFile.InputStream.CanSeek;//StreamReader sr = new StreamReader(this.FileUploadImport.PostedFile.InputStream);//update by hwx 11/12/2010
            StreamReader sr = new StreamReader(inputStream);
            int iColumnCount = 19;//the column count in the file
            int iRow = 1;// the row number is being read
            int iColumn = 0;// the column number is being read
            string strStandardTitle = string.Empty; // the title as it is
            //read title row
            string strTitle = sr.ReadLine();
            //string[] strRowTitle = strTitle.Split(new char[] { ',' });
            string[] strRowTitle = new string[iColumnCount];
            string strCharTitle;
            int iCellNumberTitle = 0;
            bool blnQuoteTitle = false;
            for (int i = 0; i < strTitle.Length; i++)
            {
                strCharTitle = strTitle.Substring(i, 1);
                if (strCharTitle == ",")// "," is the seperation symbol of csv file,
                {
                    if (!blnQuoteTitle)
                    {
                        iCellNumberTitle++;// out of the "" range, "," is the seperation symbol
                        if (iCellNumberTitle >= iColumnCount)// too many column in this line
                        {
                            break;
                        }
                    }
                    else
                    {
                        strRowTitle[iCellNumberTitle] += strCharTitle;
                    }
                }
                else if (strCharTitle == "\"")// "\"" is the transfer symbol of csv file,
                {
                    blnQuoteTitle = !blnQuoteTitle;
                    if (blnQuoteTitle && i > 0 && strTitle.Substring(i - 1, 1) == "\"")//in the "" range and there is an transfer symbol before
                    {
                        strRowTitle[iCellNumberTitle] += strCharTitle;
                    }
                }
                else
                {
                    strRowTitle[iCellNumberTitle] += strCharTitle;
                }
            }
            //read the content
            if (strRowTitle.Length == iColumnCount)
            {
                foreach (string strCell in strRowTitle)
                {
                    iColumn++;
                    if (strCell.Trim() != string.Empty)
                    {
                        dtFile.Columns.Add(strCell);//add new column with name to the data table
                    }
                    else //file error:blank title
                    {
                        errMessage += "The cell " + iColumn.ToString() + " is blank in the header row.\r\n";
                    }
                }
                if (dtFile.Columns.Count == iColumnCount)

//make sure that no blank header or error header
                {
                    //read content row
                    string strLine;
                    while (!sr.EndOfStream)
                    {
                        iRow++;
                        iColumn = 0;
                        DataRow dr = dtFile.NewRow();
                        strLine = sr.ReadLine();

//read csv file line by line
                        string[] strRow = new string[iColumnCount];
                        string strChar;
                        int iCellNumber = 0;
                        bool blnQuote = false;//whether in the "" range
                        for (int i = 0; i < strLine.Length; i++)
                        {
                            strChar = strLine.Substring(i, 1);
                            if (strChar == ",")// "," is the seperation symbol of csv file,
                            {
                                if (!blnQuote)
                                {
                                    iCellNumber++;// out of the "" range, "," is the seperation symbol
                                    if (iCellNumber >= iColumnCount)//too many column in this line
                                    {
                                        break;
                                    }
                                }
                                else
                                {
                                    strRow[iCellNumber] += strChar;
                                }
                            }
                            else if (strChar == "\"")// "\"" is the transfer symbol of csv file,
                            {
                                blnQuote = !blnQuote;
                                if (blnQuote && i > 0 && strLine.Substring(i - 1, 1) == "\"")//in the "" range and there is an transfer symbol before
                                {
                                    strRow[iCellNumber] += strChar;
                                }
                            }
                            else
                            {
                                strRow[iCellNumber] += strChar;
                            }
                        }
                        if (iCellNumber + 1 == iColumnCount)
                        {
                            foreach (string strCell in strRow)
                            {
                                iColumn++;
                                if (strCell != null && strCell.Trim() != string.Empty)
                                {
                                    dr[strRowTitle[iColumn - 1]] = strCell.Trim();
                                }
                                else//file error:blank cell
                                {
                                    dr[strRowTitle[iColumn - 1]] = String.Empty;
                                    //errMessage += "The column \"" + strRowTitle[iColumn - 1] + "\" is blank in row " + iRow.ToString() + ".\r\n";
                                }
                            }
                        }
                        else// file error:the column count of current row do not equal to title's
                        {
                            errMessage += "There are more or less cells than title row in the row " + iRow.ToString() + ".\r\n";
                        }
                        dtFile.Rows.Add(dr);
                    }
                }
            }
            else //file error:the count of columns in the file don't equal it should be
            {
                errMessage += "There are an incorrect number of columns in the header row compared to the template file.\r\n";
            }
            sr.Close();
            sr.Dispose();

errMessage = errMessage.Replace("\r\n", "<br>");
            return errMessage == String.Empty ? true : false;
        }

/// <summary>
        /// Get dataset from csv file.
        /// </summary>
        /// <param name="filepath">http://www.nuoya118.com</param>
        /// <param name="filename"></param>
        /// <returns>Data Set</returns>
        private DataSet GetDatasetFromCsv(string filepath, string filename)
        {
            string strconn = @"driver={microsoft text driver (*.txt; *.csv)};dbq=";
            strconn += filepath;                                                        //filepath, for example: c:\
            strconn += ";extensions=asc,csv,tab,txt;";
            OdbcConnection objconn = new OdbcConnection(strconn);
            DataSet dscsv = new DataSet();
            try
            {
                string strsql = "select * from " + filename;                     //filename, for example: 1.csv
                OdbcDataAdapter odbccsvdataadapter = new OdbcDataAdapter(strsql, objconn);

odbccsvdataadapter.Fill(dscsv);
                return dscsv;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

csv导出代码

/// <summary>
        /// Export to Csv File from dataset
        /// </summary>
        /// <param name="src"></param>
        /// <param name="folderName">folderName</param>
        /// <param name="strFileName">strFileName</param>
        /// <returns></returns>
        public bool ExportToCsv(DataSet src, string folderName, string strFileName)
        {
            string csv = String.Empty;

StreamWriter writer = null;

string fileName = Server.MapPath("/") + folderName + "\\" + strFileName;

try
            {
                if (src == null || src.Tables.Count == 0) throw new Exception("dataset is null or has not table in dataset");

for (int i = 0; i < src.Tables.Count; i++)
                {

if (i > 0)

fileName = fileName.Substring(0, fileName.IndexOf('.')) + i + fileName.Substring(fileName.IndexOf("."));
                    writer = new StreamWriter(fileName);
                    DataTable dt = src.Tables[i];
                    StringBuilder sb = new StringBuilder();
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        string colName = dt.Columns[j].ColumnName;
                        if (colName.IndexOf(',') > -1)
                        colName = colName.Insert(0, "\"").Insert(colName.Length + 1, "\"");
                        sb.Append(colName);
                        if (!colName.Equals(""))
                            if (j != dt.Columns.Count - 1)
                                sb.Append(",");
                    }
                    writer.WriteLine(sb.ToString());
                    sb = new StringBuilder();
                    string temp = "";
                    for (int j = 0; j < dt.Rows.Count; j++)
                    {
                        DataRow dr = dt.Rows[j];
                        for (int k = 0; k < dt.Columns.Count; k++)
                        {
                            object o = dr[k];
                            if (o != null)
                                temp = o.ToString();
                            if (temp.IndexOf(',') > -1)
                                temp = temp.Insert(0, "\"").Insert(temp.Length + 1, "\"");
                            sb.Append(temp);
                            if (k != dt.Columns.Count - 1)
                                sb.Append(",");
                        }
                        writer.WriteLine(sb.ToString());
                        sb = new StringBuilder();
                        csv = sb.ToString();
                    }
                    writer.Close();
                }

string strFilePath = Server.MapPath("/") + folderName;
                if (!Directory.Exists(strFilePath))
                {
                    Directory.CreateDirectory(strFilePath);
                }

strFullFileName = Server.MapPath("/") + folderName + "\\" + fileName;
                //FullFileName = Server.MapPath(FileName);
                //FileName
                FileInfo DownloadFile = new FileInfo(strFullFileName);
                if (DownloadFile.Exists)
                {
                    Response.Clear();
                    Response.ClearHeaders();
                    Response.Buffer = false;
                    Response.ContentType = "application/octet-stream";
                    //Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(DownloadFile.FullName, System.Text.Encoding.ASCII));
                    Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.ASCII));
                    Response.AppendHeader("Content-Length", DownloadFile.Length.ToString());
                    Response.WriteFile(DownloadFile.FullName);
                    Response.Flush();
                    //Response.End();
                }
                else
                {
                    //not exist
                    throw new Exception("Export csv file does not exist!");
                }

}

catch (Exception ex)
            {
                throw new Exception("Save csv error", ex);
            }

finally
            {
                if (writer != null) writer.Close();
            }
            return true;
        }

/// <summary>
        /// List to DataTable
        /// </summary>
        /// <param name="entitys">entitys list</param>
        /// <returns></returns>
        public DataTable ListToDataTable(List<T> entitys)
        {
            if (entitys == null || entitys.Count < 1)
            {
                throw new Exception("list is null");
            }
            //get first Propertie
            Type entityType = entitys[0].GetType();
            PropertyInfo[] entityProperties = entityType.GetProperties();
            //DataTable structure
            //
            DataTable dt = new DataTable();
            for (int i = 0; i < entityProperties.Length; i++)
            {
                //dt.Columns.Add(entityProperties[i].Name, entityProperties[i].PropertyType);
                dt.Columns.Add(entityProperties[i].Name);
            }
            //add entity to DataTable
            foreach (object entity in entitys)
            {
                //check type
                if (entity.GetType() != entityType)
                {
                    throw new Exception("type not same");
                }
                object[] entityValues = new object[entityProperties.Length];
                for (int i = 0; i < entityProperties.Length; i++)
                {
                    entityValues[i] = entityProperties[i].GetValue(entity, null);
                }
                dt.Rows.Add(entityValues);
            }
            return dt;
        }

.NET中的CSV导入导出(实例)的更多相关文章

  1. AngularJS中module的导入导出

    关于AngularJS中module的导入导出,在Bob告诉我之前还没写过,谢谢Bob在这方面的指导,给到我案例代码. 在AngularJS实际项目中,我们可能需要把针对某个领域的各个方面放在不同的m ...

  2. oracle数据库的导入 导出实例

    oracle数据库的导入 导出实例 分类: DataBase2011-09-07 23:25 377人阅读 评论(0) 收藏 举报 数据库oraclefileusercmdservice 我要从另外一 ...

  3. ASP.NET 开源导入导出库Magicodes.IE 完成Csv导入导出

    Magicodes.IE Csv导入导出 说明 本章主要说明如何使用Magicodes.IE.Csv进行Csv导入导出. 主要步骤 1.安装包Magicodes.IE.Csv Install-Pack ...

  4. sqlserver中BCP命令导入导出

    个人自用导出文本文件命令: bcp [xxDB].[dbo].[xx_tb_name] out d:\temp\xxx.txt -c -t "\t" -T bcp是SQL Serv ...

  5. oracle 中数据库完全导入导出:cmd命令行模式(转载)

    http://www.3lian.com/edu/2012/12-01/47252.html Oracle数据导入导出imp/exp就相当于oracle数据还原与备份.exp命令可以把数据从远程数据库 ...

  6. NPOI 操作数据库中数据的导入导出(Excel.xls文件) 和null数据的处理。

    App.config: <?xml version="1.0" encoding="utf-8" ?> <configuration> ...

  7. jxl导入导出实例

    1 package com.tgb.test; 2 3 import java.io.File; 4 import java.io.IOException; 5 import java.util.Ar ...

  8. java实现文件批量导入导出实例(兼容xls,xlsx)

    1.介绍 java实现文件的导入导出数据库,目前在大部分系统中是比较常见的功能了,今天写个小demo来理解其原理,没接触过的同学也可以看看参考下. 目前我所接触过的导入导出技术主要有POI和iRepo ...

  9. java 中Excel的导入导出

    部分转发原作者https://www.cnblogs.com/qdhxhz/p/8137282.html雨点的名字  的内容 java代码中的导入导出 首先在d盘创建一个xlsx文件,然后再进行一系列 ...

随机推荐

  1. [每日一题] OCP1z0-047 :2013-07-27 外部表――不能被DML和建索引

    首先看官方文档上的解释: Managing External Tables Oracle Database allows you read-only access to data in externa ...

  2. vim 快捷键大全

    一.移动光标 1.左移h.右移l.下移j.上移k 2.向下翻页ctrl + f,向上翻页ctrl + b 3.向下翻半页ctrl + d,向上翻半页ctrl + u 4.移动到行尾$,移动到行首0(数 ...

  3. Swift学习之函数和简单地控件的创建

     今天还是重复昨天做的事情--敲代码,但唯一的不同就是所学的知识不同了,我们又进一步往深得层次学习了,感觉越来越有意思了,虽然临近结束了看着大家积极性越来越低了,但是我知道我不能这样,我要比别人付出的 ...

  4. 面试前的准备---C#知识点回顾----04

    播下的种子,慢慢开始发芽收获了,陆陆续续offer就来了,该轮到我挑的时候了 今天面试的一家公司,技术问的相对宽广和细致,程度令人发指 1.谈谈ViewState 这个问题,回答的好,工资翻一级 基本 ...

  5. Android 平滑图片加载和缓存库 Glide 使用详解

    在图片加载库烂大街的今天,选择一个适合自己使用的图片加载库已经成为了每一个Android开发者的必经之路.现在市面上知名的图片加载库有UIL,Picasso,Volley ImageLoader,Fr ...

  6. 几句话弄清楚Java参数传值还是传引用

    最近刷题做了一些算法题,对于在递归函数调用的时候什么时候传入值,什么时候传入引用有疑问,在网上搜索了一下,得出了一下三条总结: 1.对象就是传引用 2.原始类型就是传值 3.String,Intege ...

  7. Oracle 回忆录

    简述 工作时间说短也不算短了,掐指一算差不多三年了吧.以前都没有写过Blog,仅偶尔对所学和所用到的做些许整理,后面竟然没有把那留下来,悲催啊!留不下来的整理不是好东西(*^__^*) 嘻嘻……,现在 ...

  8. 浅析Struts1和Struts2的Action线程安全问题

    tomcat容器对servlet的实现采用的是单例模式,对于一个servlet类,永远只有一个servlet对象存在. 下面我们来解释为什么Struts1是线程不安全的. 1.Struts1 Stru ...

  9. hdu 1587

    Problem Description As you know, Gardon trid hard for his love-letter, and now he's spending too muc ...

  10. tomcat解决乱码

    今天遇到个问题,太尴尬了: 本来做好并测试号的项目提交到svn, 组员下了之后,又部分url传递的中文参数在另一个jsp接收出现乱码(只有我的不乱码). 改了之后更尴尬的事情发生了:组员的全部不乱码, ...