0

I wanted to write to a specific sheet of an excel file having multiple sheets. How can I do so using C#. This is the method that I have:

public void WriteCSV<T>(IEnumerable<T> items, string path, StringBuilder stringBuilder)
        {
            var csvFileLength = new System.IO.FileInfo(path).Length;
                var csv = stringBuilder;
            
            Type itemType = typeof(T);
            var props = itemType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
            //
            using (StreamWriter sw = new StreamWriter(path, true))
            {
                if (csvFileLength <= 2)
                {
                    sw.WriteLine(string.Join(", ", props.Select(p => p.Name)));
                }
                foreach (var item in items)
                {
                    sw.WriteLine(string.Join(", ", props.Select(p => p.GetValue(item, null))));
                    //var newLine = string.Format(write, Environment.NewLine);
                    //csv.Append(newLine);
                    //File.WriteAllText(path, csv.ToString());
                }

            }
wax
  • 43
  • 5
  • The code above will create a CSV file only. CSV and Excel are totally different types of file. If you want to create an Excel file then use an Excel-specific library such as EPPlus or NPOI. Most of the code you've written above will not be relevant. – ADyson Sep 16 '20 at 14:01
  • 1
    More details here: [How do I create an Excel (.XLS and .XLSX) file in C# without installing Microsoft Office?](https://stackoverflow.com/questions/151005/how-do-i-create-an-excel-xls-and-xlsx-file-in-c-sharp-without-installing-mic) . Did you any research of your own? If you'd googled your requirement you should have found this information (and plenty of other resources) already. – ADyson Sep 16 '20 at 14:01
  • @ADyson many people don't know the difference between CSV and Excel, they assume that if you can open it with Excel, it's Excel. Developers are some of the worst offenders as they seldom use spreadsheets or other "business" applications. Have you ever tried to export eg the guest list for a Meetup event? Noticed it's a CSV with a fake `.xls` extension? – Panagiotis Kanavos Sep 16 '20 at 14:29
  • @PanagiotisKanavos I haven't done that specific process, no. But I'm aware people often don't understand that CSV is different. Since OP's question is "write to a specific sheet of an **excel** file" then I'd hope that googling that would get them the relevant info, since it doesn't even mention CSV. The only mention of CSV is in their code. (O.P. did ask a now-deleted question yesterday where it was clear they didn't understand this distinction, but it was explained to them, sufficiently they're now asking this question, but it seems their research skills still need some work, as well :-)) – ADyson Sep 16 '20 at 14:39

0 Answers0