zoukankan      html  css  js  c++  java
  • .NET中的CSV导入导出

    导入代码,从csv文件得到datatable
    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 == 0throw 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;
            }
  • 相关阅读:
    Python中文乱码(转)
    一千行MySQL学习笔记
    pycharm在同目录下import,pycharm会提示错误,但是可以运行
    PyCharm3.0默认快捷键
    Sublime Text 3 快捷键
    window下spyder的快捷键
    Anaconda更新和第三方包更新
    PyCharm 教程
    centos7.9 源码编译安装php
    centos7.9 源码编译安装nginx
  • 原文地址:https://www.cnblogs.com/ColdFish_Pegasus/p/2217977.html
Copyright © 2011-2022 走看看