creating csv based on certain key of db table

gal mor 141 Reputation points
2022-12-12T08:26:43.14+00:00

hello, I have the following code:

269547-function.png

which will generate the following table :

269530-ll.png

into a csv file:

269568-csv.png

I want to split that csv into different CSVs using COMPANY_ID column as identifier.
for example,
first file will be named COMPANY_ID10.CSV with content -> (notice the companyID columns which is 10)
269622-comid10.png

and so on as per companyID. how should I approach it? thanks

SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
12,759 questions
.NET CLI
.NET CLI
A cross-platform toolchain for developing, building, running, and publishing .NET applications.
323 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,279 questions
{count} votes

3 answers

Sort by: Most helpful
  1. Jack J Jun 24,296 Reputation points Microsoft Vendor
    2022-12-12T09:52:53.86+00:00

    @gal mor , Welcome to Microsoft Q&A, I recommend that you could convert your current csv to many datatables group by Company_ID, then you could convert these datatables to csv files.

    Here is a code example you could refer to.

    static void Main(string[] args)  
            {  
                var dt = ConvertCSVtoDataTable("test.csv");  
                var result = from rows in dt.AsEnumerable()  
                             group rows by rows["Company_ID"]  
                             into grp  
                             select grp;  
                foreach (var item in result)  
                {  
                    DataTable newdt = item.CopyToDataTable();  
                    StringBuilder sb = new StringBuilder();  
      
                    IEnumerable<string> columnNames = newdt.Columns.Cast<DataColumn>().  
                                                      Select(column => column.ColumnName);  
                    sb.AppendLine(string.Join(",", columnNames));  
      
                    foreach (DataRow row in newdt.Rows)  
                    {  
                        IEnumerable<string> fields = row.ItemArray.Select(field => field.ToString());  
                        sb.AppendLine(string.Join(",", fields));  
                    }  
      
                    File.WriteAllText("CompanyID" + item.Key + ".csv", sb.ToString());  
      
                }  
                 
            }  
            public static DataTable ConvertCSVtoDataTable(string strFilePath)  
            {  
                DataTable dt = new DataTable();  
                using (StreamReader sr = new StreamReader(strFilePath))  
                {  
                    string[] headers = sr.ReadLine().Split(',');  
                    foreach (string header in headers)  
                    {  
                        dt.Columns.Add(header);  
                    }  
                    while (!sr.EndOfStream)  
                    {  
                        string[] rows = sr.ReadLine().Split(',');  
                        DataRow dr = dt.NewRow();  
                        for (int i = 0; i < headers.Length; i++)  
                        {  
                            dr[i] = rows[i];  
                        }  
                        dt.Rows.Add(dr);  
                    }  
      
                }  
      
      
                return dt;  
            }  
    

    Hope my solution could help you.

    Best Regards,
    Jack


    If the answer is the right solution, please click "Accept Answer" and upvote it.If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    2 people found this answer helpful.

  2. Bjoern Peters 8,781 Reputation points
    2022-12-12T08:54:29.357+00:00

    Hi @gal mor

    How do you call that function "ExportExcel"?

    First suggestion, as that function needs to receive three parameters... relevant => DataTable and Filename.

    During creating that DataTable, implement a filter like "get all company_ids, create a DataTable for each company_id," and export each DataTable. Also, build the Filename based on company_id.


  3. gal mor 141 Reputation points
    2022-12-20T14:39:58.923+00:00

    Sorry I forgot to reply. I was using the logic of the code, and it was helpful. thanks a lot.
    If you're interested I ended up doing:

     void CreateCsvForEachCompany(Dictionary<int, List<RecordObject>> dict)  
                {  
                    //for every company in dictionary we create a csv  
                    foreach (KeyValuePair<int, List<RecordObject>> entry in dict)  
                    {  
                        int key = entry.Key;  
                        List<RecordObject> value = entry.Value;  
                        string filePath = "D:/CompaniesRecordsByObj/";  
                        string fileName = key.ToString() + ".CSV";  
      
                        int length = entry.Value.Count;  
                        StreamWriter writer = new StreamWriter(filePath + fileName, true, Encoding.Default);  
                        StringBuilder csv = new StringBuilder();  
                        GetObjectPropertiesForSecondRow(csv);  
      
                        foreach (RecordObject record in value)  
                        {  
                            writer.WriteLine(record.OrderCompanyId + "," + record.OrderBtlId + "," + record.Zehut + "," + record.CreateDate + "," + record.TimeStamp + "," + record.Interface);  
                        }  
                        writer.Close();  
                    }  
                }  
      
      
    
    0 comments No comments