CSV Excel फ़ाइल C # कैसे बनाएँ? [बन्द है]


132

मैं सीएसवी एक्सेल फाइल बनाने के लिए एक क्लास की तलाश में हूं।

अपेक्षित विशेषताएं:

  • उपयोग करने के लिए बेहद सरल है
  • कोमा से बाहर निकलता है और उद्धरण तो उत्कृष्ट उन्हें ठीक संभालती है
  • समय-प्रूफ प्रारूप में निर्यात की तारीख और डेटाटाइम्स

क्या आप इसके लिए सक्षम किसी वर्ग को जानते हैं?


12
प्रश्न को प्रश्न के भाग में रखने के लिए बेहतर है, और फिर जवाब में अपना जवाब पोस्ट करें। प्रश्न में टैग और कीवर्ड जोड़ना सुनिश्चित करें, इसे खोज योग्य बनाने के लिए।
चीजो

महत्वपूर्ण: आपको "मूल्य" में CARRAGE RETURNS के उद्धरण भी जोड़ने चाहिए।
एलेक्स

धन्यवाद @ क्रिस, एक सुझाव अगर मैं कर सकता हूं, तो यह कोड KeyNotFoundException को फेंक सकता है, कृपया मेरा उत्तर देखें।
जोसेफ

इसका सबसे अच्छा उदाहरण ... लेकिन मैं एकल फ़ाइल में दो तालिका कैसे जोड़ सकता हूं, इसका मतलब है कि मेरे पास दो पंक्तियों की एक तालिका है और अन्य तालिका 10 पंक्तियाँ हैं और दोनों में अद्वितीय स्तंभ नाम है। मैं शीर्ष और बाद में दो पंक्तियों की तालिका जोड़ना चाहता हूं दो पंक्तियों का अंतर मैं दूसरी तालिका जोड़ना चाहता हूं।
फ़्लोकी

जवाबों:


92

थोड़ा अलग संस्करण मैंने अपनी आवश्यकताओं के लिए प्रतिबिंब का उपयोग करके लिखा। मुझे सीएसवी को वस्तुओं की एक सूची का निर्यात करना पड़ा। मामले में कोई इसे भविष्य के लिए उपयोग करना चाहता है।

public class CsvExport<T> where T: class
    {
        public List<T> Objects;

        public CsvExport(List<T> objects)
        {
            Objects = objects;
        }

        public string Export()
        {
            return Export(true);
        }

        public string Export(bool includeHeaderLine)
        {

            StringBuilder sb = new StringBuilder();
            //Get properties using reflection.
            IList<PropertyInfo> propertyInfos = typeof(T).GetProperties();

            if (includeHeaderLine)
            {
                //add header line.
                foreach (PropertyInfo propertyInfo in propertyInfos)
                {
                    sb.Append(propertyInfo.Name).Append(",");
                }
                sb.Remove(sb.Length - 1, 1).AppendLine();
            }

            //add value for each property.
            foreach (T obj in Objects)
            {               
                foreach (PropertyInfo propertyInfo in propertyInfos)
                {
                    sb.Append(MakeValueCsvFriendly(propertyInfo.GetValue(obj, null))).Append(",");
                }
                sb.Remove(sb.Length - 1, 1).AppendLine();
            }

            return sb.ToString();
        }

        //export to a file.
        public void ExportToFile(string path)
        {
            File.WriteAllText(path, Export());
        }

        //export as binary data.
        public byte[] ExportToBytes()
        {
            return Encoding.UTF8.GetBytes(Export());
        }

        //get the csv value for field.
        private string MakeValueCsvFriendly(object value)
        {
            if (value == null) return "";
            if (value is Nullable && ((INullable)value).IsNull) return "";

            if (value is DateTime)
            {
                if (((DateTime)value).TimeOfDay.TotalSeconds == 0)
                    return ((DateTime)value).ToString("yyyy-MM-dd");
                return ((DateTime)value).ToString("yyyy-MM-dd HH:mm:ss");
            }
            string output = value.ToString();

            if (output.Contains(",") || output.Contains("\""))
                output = '"' + output.Replace("\"", "\"\"") + '"';

            return output;

        }
    }

उपयोग नमूना: (प्रति टिप्पणी अद्यतन)

CsvExport<BusinessObject> csv= new CsvExport<BusinessObject>(GetBusinessObjectList());
Response.Write(csv.Export());

5
यह इस तरह से अधिक था: सूची <BusinessObject> x = नई सूची <BusinessObject> (); CsvExport <BusinessObject> x = new CsvExport <BusinessObject> (MUsers);
छिपा

5
आपका अतुलनीय इंटरफ़ेस कहाँ से आया?
किलाफर

इसका सबसे अच्छा उदाहरण ... लेकिन मैं एकल फ़ाइल में दो तालिका कैसे जोड़ सकता हूं, इसका मतलब है कि मेरे पास दो पंक्तियों की एक तालिका है और अन्य तालिका 10 पंक्तियाँ हैं और दोनों में अद्वितीय स्तंभ नाम है। मैं शीर्ष और बाद में दो पंक्तियों की तालिका जोड़ना चाहता हूं दो पंक्तियों का अंतर मैं दूसरी तालिका जोड़ना चाहता हूं।
फ़्लोकी

2
मुझे पता है कि मूल पोस्ट 2011 से थी, इसलिए मुझे यकीन नहीं है कि यह .NET संस्करण में संभव था जो कि तब वापस उपयोग किया गया था। लेकिन क्यों नहीं public string Export()विधि को हटा दें और public string Export(bool includeHeaderLiner = true)(डिफ़ॉल्ट पैरामीटर मान के साथ) अन्य विधि को बदलें । फिर से, मुझे यकीन नहीं है कि 2011 में डिफ़ॉल्ट पैरामीटर उपलब्ध थे, लेकिन वर्तमान कोड मेरे लिए ऑनरोथोडॉक्स दिखता है।
केविन क्रूज़सेन

19

कृपया मुझे माफ़ करें

लेकिन मुझे लगता है कि एक सार्वजनिक ओपन-सोर्स रिपॉजिटरी कोड को साझा करने और योगदान देने और सुधार करने का एक बेहतर तरीका है, और इसके अतिरिक्त "जैसे मैंने इसे ठीक किया, मैंने तय किया"

इसलिए मैंने विषय-स्टार्टर के कोड और सभी अतिरिक्त में से एक सरल git-repository बनाया:

https://github.com/jitbit/CsvExport

मैंने स्वयं कुछ उपयोगी फ़िक्सेस जोड़े। हर कोई सुझाव जोड़ सकता है, इसे योगदान करने के लिए कांटा आदि आदि मुझे अपने कांटे भेजें ताकि मैं उन्हें रेपो में वापस मिला दूं।

पुनश्च। मैंने क्रिस के लिए सभी कॉपीराइट नोटिस पोस्ट किए। @ अगर आप इस विचार के खिलाफ हैं - मुझे बताइए, मैं इसे मार डालूँगा।


11

CSV- फ़ाइलों को पढ़ने और लिखने का एक और अच्छा समाधान है फ़ाइललेपर्स (खुला स्रोत)।


NB: एक्सेल समर्थन केवल बुनियादी परिदृश्यों के लिए है : वर्तमान कार्यान्वित एक्सेल समर्थन केवल मूल परिदृश्यों के लिए है। यदि आपको कस्टम स्वरूपण, चार्ट आदि की आवश्यकता है, तो आपको कस्टम कोड के लिए जाना चाहिए। यह एनपीओआई लाइब्रेरी का सीधे उपयोग करने की दृढ़ता से सिफारिश की गई है
एके

6

कैसे के बारे में string.Join का उपयोग करने के बजाय सभी foreach लूप्स?


String.Join केवल स्ट्रिंग [] पर काम करता है, जबकि मैं सूची <string> की कुछ विशेषताओं का उपयोग कर रहा हूं।
क्रिस

12
String.Join("," , List<string>)काम भी करता है।
देहाती

6

अगर किसी को मैं IEnumerable पर एक विस्तार विधि में परिवर्तित करना चाहते हैं:

public static class ListExtensions
{
    public static string ExportAsCSV<T>(this IEnumerable<T> listToExport, bool includeHeaderLine, string delimeter)
    {
        StringBuilder sb = new StringBuilder();

        IList<PropertyInfo> propertyInfos = typeof(T).GetProperties();

        if (includeHeaderLine)
        {
            foreach (PropertyInfo propertyInfo in propertyInfos)
            {
                sb.Append(propertyInfo.Name).Append(",");
            }
            sb.Remove(sb.Length - 1, 1).AppendLine();
        }

        foreach (T obj in listToExport)
        {
            T localObject = obj;

            var line = String.Join(delimeter, propertyInfos.Select(x => SanitizeValuesForCSV(x.GetValue(localObject, null), delimeter)));

            sb.AppendLine(line);
        }

        return sb.ToString();
    }

    private static string SanitizeValuesForCSV(object value, string delimeter)
    {
        string output;

        if (value == null) return "";

        if (value is DateTime)
        {
            output = ((DateTime)value).ToLongDateString();
        }
        else
        {
            output = value.ToString();                
        }

        if (output.Contains(delimeter) || output.Contains("\""))
            output = '"' + output.Replace("\"", "\"\"") + '"';

        output = output.Replace("\n", " ");
        output = output.Replace("\r", "");

        return output;
    }
}

5

इस वर्ग पर बहुत अच्छा काम किया। उपयोग में सरल और आसान। मैंने निर्यात की पहली पंक्ति में एक शीर्षक शामिल करने के लिए कक्षा को संशोधित किया; मुझे लगा कि मैं साझा करूंगा:

उपयोग:

CsvExport myExport = new CsvExport();
myExport.addTitle = String.Format("Name: {0},{1}", lastName, firstName));

वर्ग:

public class CsvExport
{
    List<string> fields = new List<string>();

    public string addTitle { get; set; } // string for the first row of the export

    List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
    Dictionary<string, object> currentRow
    {
        get
        {
            return rows[rows.Count - 1];
        }
    }

    public object this[string field]
    {
        set
        {
            if (!fields.Contains(field)) fields.Add(field);
            currentRow[field] = value;
        }
    }

    public void AddRow()
    {
        rows.Add(new Dictionary<string, object>());
    }

    string MakeValueCsvFriendly(object value)
    {
        if (value == null) return "";
        if (value is Nullable && ((INullable)value).IsNull) return "";
        if (value is DateTime)
        {
            if (((DateTime)value).TimeOfDay.TotalSeconds == 0)
                return ((DateTime)value).ToString("yyyy-MM-dd");
            return ((DateTime)value).ToString("yyyy-MM-dd HH:mm:ss");
        }
        string output = value.ToString();
        if (output.Contains(",") || output.Contains("\""))
            output = '"' + output.Replace("\"", "\"\"") + '"';
        return output;

    }

    public string Export()
    {
        StringBuilder sb = new StringBuilder();

        // if there is a title
        if (!string.IsNullOrEmpty(addTitle))
        {
            // escape chars that would otherwise break the row / export
            char[] csvTokens = new[] { '\"', ',', '\n', '\r' };

            if (addTitle.IndexOfAny(csvTokens) >= 0)
            {
                addTitle = "\"" + addTitle.Replace("\"", "\"\"") + "\"";
            }
            sb.Append(addTitle).Append(",");
            sb.AppendLine();
        }


        // The header
        foreach (string field in fields)
        sb.Append(field).Append(",");
        sb.AppendLine();

        // The rows
        foreach (Dictionary<string, object> row in rows)
        {
            foreach (string field in fields)
                sb.Append(MakeValueCsvFriendly(row[field])).Append(",");
            sb.AppendLine();
        }

        return sb.ToString();
    }

    public void ExportToFile(string path)
    {
        File.WriteAllText(path, Export());
    }

    public byte[] ExportToBytes()
    {
        return Encoding.UTF8.GetBytes(Export());
    }
}


3

मैंने ExportToStream को जोड़ा ताकि csv को पहले हार्ड ड्राइव में सहेजना न पड़े।

public Stream ExportToStream()
{
    MemoryStream stream = new MemoryStream();
    StreamWriter writer = new StreamWriter(stream);
    writer.Write(Export(true));
    writer.Flush();
    stream.Position = 0;
    return stream;
}

3

मैंने जोड़ लिया है

public void ExportToFile(string path, DataTable tabela)
{

     DataColumnCollection colunas = tabela.Columns;

     foreach (DataRow linha in tabela.Rows)
     {

           this.AddRow();

           foreach (DataColumn coluna in colunas)

           {

               this[coluna.ColumnName] = linha[coluna];

           }

      }
      this.ExportToFile(path);

}

पिछला कोड पुराने .NET संस्करणों के साथ काम नहीं करता है। 3.5 संस्करण के लिए इस अन्य संस्करण का उपयोग करें:

        public void ExportToFile(string path)
    {
        bool abort = false;
        bool exists = false;
        do
        {
            exists = File.Exists(path);
            if (!exists)
            {
                if( !Convert.ToBoolean( File.CreateText(path) ) )
                        abort = true;
            }
        } while (!exists || abort);

        if (!abort)
        {
            //File.OpenWrite(path);
            using (StreamWriter w = File.AppendText(path))
            {
                w.WriteLine("hello");
            }

        }

        //File.WriteAllText(path, Export());
    }

2

इसके लिए बहुत धन्यवाद! मैंने कक्षा को संशोधित किया:

  • कोड में हार्डकोड के बजाय एक चर सीमांकक का उपयोग करें
  • सभी newLines (\ n \ r \ n \ r) को प्रतिस्थापित करना MakeValueCsvFriendly

कोड:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Data.SqlTypes;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;

    public class CsvExport
    {

        public char delim = ';';
        /// <summary>
        /// To keep the ordered list of column names
        /// </summary>
        List<string> fields = new List<string>();

        /// <summary>
        /// The list of rows
        /// </summary>
        List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();

        /// <summary>
        /// The current row
        /// </summary>
        Dictionary<string, object> currentRow { get { return rows[rows.Count - 1]; } }

        /// <summary>
        /// Set a value on this column
        /// </summary>
        public object this[string field]
        {
            set
            {
                // Keep track of the field names, because the dictionary loses the ordering
                if (!fields.Contains(field)) fields.Add(field);
                currentRow[field] = value;
            }
        }

        /// <summary>
        /// Call this before setting any fields on a row
        /// </summary>
        public void AddRow()
        {
            rows.Add(new Dictionary<string, object>());
        }

        /// <summary>
        /// Converts a value to how it should output in a csv file
        /// If it has a comma, it needs surrounding with double quotes
        /// Eg Sydney, Australia -> "Sydney, Australia"
        /// Also if it contains any double quotes ("), then they need to be replaced with quad quotes[sic] ("")
        /// Eg "Dangerous Dan" McGrew -> """Dangerous Dan"" McGrew"
        /// </summary>
        string MakeValueCsvFriendly(object value)
        {
            if (value == null) return "";
            if (value is INullable && ((INullable)value).IsNull) return "";
            if (value is DateTime)
            {
                if (((DateTime)value).TimeOfDay.TotalSeconds == 0)
                    return ((DateTime)value).ToString("yyyy-MM-dd");
                return ((DateTime)value).ToString("yyyy-MM-dd HH:mm:ss");
            }
            string output = value.ToString();
            if (output.Contains(delim) || output.Contains("\""))
                output = '"' + output.Replace("\"", "\"\"") + '"';
            if (Regex.IsMatch(output,  @"(?:\r\n|\n|\r)"))
                output = string.Join(" ", Regex.Split(output, @"(?:\r\n|\n|\r)"));
            return output;
        }

        /// <summary>
        /// Output all rows as a CSV returning a string
        /// </summary>
        public string Export()
        {
            StringBuilder sb = new StringBuilder();

            // The header
            foreach (string field in fields)
                sb.Append(field).Append(delim);
            sb.AppendLine();

            // The rows
            foreach (Dictionary<string, object> row in rows)
            {
                foreach (string field in fields)
                    sb.Append(MakeValueCsvFriendly(row[field])).Append(delim);
                sb.AppendLine();
            }

            return sb.ToString();
        }

        /// <summary>
        /// Exports to a file
        /// </summary>
        public void ExportToFile(string path)
        {
            File.WriteAllText(path, Export());
        }

        /// <summary>
        /// Exports as raw UTF8 bytes
        /// </summary>
        public byte[] ExportToBytes()
        {
            return Encoding.UTF8.GetBytes(Export());

        }

    }


1

मूल वर्ग में एक समस्या है, और यदि आप एक नया कॉलम जोड़ना चाहते हैं, तो आपको निर्यात विधि पर KeyNotFoundException प्राप्त होगी। उदाहरण के लिए:

static void Main(string[] args)
{
    var export = new CsvExport();

    export.AddRow();
    export["Region"] = "New York, USA";
    export["Sales"] = 100000;
    export["Date Opened"] = new DateTime(2003, 12, 31);

    export.AddRow();
    export["Region"] = "Sydney \"in\" Australia";
    export["Sales"] = 50000;
    export["Date Opened"] = new DateTime(2005, 1, 1, 9, 30, 0);
    export["Balance"] = 3.45f;  //Exception is throwed for this new column

    export.ExportToFile("Somefile.csv");
}

इसे हल करने के लिए, और प्रतिबिंब का उपयोग करने के @KeyboardCowboy विचार का उपयोग करते हुए, मैंने उन पंक्तियों को जोड़ने की अनुमति देने के लिए कोड को संशोधित किया जिनके पास समान कॉलम नहीं हैं। आप अनाम कक्षाओं के उदाहरणों का उपयोग कर सकते हैं। उदाहरण के लिए:

static void Main(string[] args)
{
    var export = new CsvExporter();

    export.AddRow(new {A = 12, B = "Empty"});
    export.AddRow(new {A = 34.5f, D = false});

    export.ExportToFile("File.csv");
}

आप स्रोत कोड यहाँ CsvExporter डाउनलोड कर सकते हैं । बेझिझक उपयोग करें और संशोधित करें।

अब, यदि आप जो पंक्तियाँ लिखना चाहते हैं, वे सभी एक ही वर्ग की हैं, तो मैंने सामान्य वर्ग CsvWriter.cs बनाया , जिसमें बेहतर प्रदर्शन RAM उपयोग और बड़ी फ़ाइलों को लिखने के लिए आदर्श है। निष्कर्ष यह है कि आप डेटा प्रकारों में फ़ॉर्मेटर्स जोड़ना चाहते हैं । उपयोग का एक उदाहरण:

class Program
{
    static void Main(string[] args)
    {
        var writer = new CsvWriter<Person>("Persons.csv");

        writer.AddFormatter<DateTime>(d => d.ToString("MM/dd/yyyy"));

        writer.WriteHeaders();
        writer.WriteRows(GetPersons());

        writer.Flush();
        writer.Close();
    }

    private static IEnumerable<Person> GetPersons()
    {
        yield return new Person
            {
                FirstName = "Jhon", 
                LastName = "Doe", 
                Sex = 'M'
            };

        yield return new Person
            {
                FirstName = "Jhane", 
                LastName = "Doe",
                Sex = 'F',
                BirthDate = DateTime.Now
            };
        }
    }


    class Person
    {
        public string FirstName { get; set; }

        public string LastName { get; set; }

        public char Sex  { get; set; }

        public DateTime BirthDate { get; set; }
    }

0

ऐसा करने के लिए आपको केवल 1 फ़ंक्शन की आवश्यकता है। केवल आपको करना यह है कि अपने सॉल्यूशन एक्सप्लोरर में एक फोल्डर बनाना है और वहां सीएसवी फाइल को स्टोर करना है और फिर उस फाइल को यूजर को एक्सपोर्ट करना है।

जैसा कि मेरे मामले में मेरे पास एक फ़ोल्डर डाउनलोड है। पहले मैं अपनी सारी सामग्री उस निर्देशिका को निर्यात करता हूं और फिर उपयोगकर्ता को निर्यात करता हूं। Response.end से निपटने के लिए, मैंने ThreadAbortException का उपयोग किया। तो यह मेरे समाधान में एक 100% वास्तविक और कामकाजी कार्य है।

protected void lnkExport_OnClick(object sender, EventArgs e)
{

    string filename = strFileName = "Export.csv";

    DataTable dt = obj.GetData();  

// call the content and load it into the datatable

    strFileName = Server.MapPath("Downloads") + "\\" + strFileName;

// creating a file in the downloads folder in your solution explorer

    TextWriter tw = new StreamWriter(strFileName);

// using the built in class textwriter for writing your content in the exporting file

    string strData = "Username,Password,City";

// above line is the header for your exported file. So add headings for your coloumns in excel(.csv) file and seperate them with ","

    strData += Environment.NewLine;

// setting the environment to the new line

    foreach (DataRow dr in dt.Rows)
    {
       strData += dr["Username"].ToString() + "," + dr["Password"].ToString() + "," +      dr["City"].ToString();
       strData += Environment.NewLine;
    }

// everytime when loop execute, it adds a line into the file
    tw.Write(strData);

// writing the contents in file
    tw.Close();

// closing the file
    Response.Redirect("Downloads/" + filename);

// exporting the file to the user as a popup to save as....
}
हमारी साइट का प्रयोग करके, आप स्वीकार करते हैं कि आपने हमारी Cookie Policy और निजता नीति को पढ़ और समझा लिया है।
Licensed under cc by-sa 3.0 with attribution required.