Hello
I want to add three DataTables to each of the three sheets and save them as one csv file.
How do I modify the code below?
If possible, I don't want to use the Nuget package.
// Below is This code saves one DataTable as one CSV file on one Sheet.
// Here, I want to add three DataTables to each of the three sheets and save them as one csv file.
// DataTable 1 is added to Sheet 1
// DataTable 2 is added to Sheet 2
// DataTable 3 is added to Sheet 3
// <==== Save this as one csv file
I want to add three DataTables to each of the three sheets and save them as one csv file.
How do I modify the code below?
If possible, I don't want to use the Nuget package.
C#:
public DataTable SqlDataAdapter1(string sqlString)
{
DataTable dt = new DataTable();
using (SqlConnection conn = new SqlConnection(_connectionString))
{
conn.Open();
SqlDataAdapter adapter = new SqlDataAdapter(sqlString, conn);
adapter.Fill(dt);
conn.Close();
}
return dt;
}
C#:
public void ReadData(string startdate, string enddate)
{
string sqlString = string.Format("exec dbo.usp_selectdata @startdate = '{0}', @enddate = '{1}' ", startdate, enddate);
DataTable dt = DBHandler.SqlDataAdapter1(sqlString);
string fileName = "D:\\0214.csv";
SaveCSV(fileName, dt);
}
// Below is This code saves one DataTable as one CSV file on one Sheet.
// Here, I want to add three DataTables to each of the three sheets and save them as one csv file.
// DataTable 1 is added to Sheet 1
// DataTable 2 is added to Sheet 2
// DataTable 3 is added to Sheet 3
// <==== Save this as one csv file
C#:
public bool SaveCSV(string fileName, DataTable table)
{
List<string> buff = new List<string>();
string[] columnNames = table.Columns.Cast<DataColumn>().
Select(column => column.ColumnName).
ToArray();
string line = string.Join(",", columnNames);
buff.Add(line);
foreach (DataRow row in table.Rows)
{
string[] fields = row.ItemArray.Select(field => field.ToString()).
ToArray();
line = string.Join(",", fields);
buff.Add(line);
}
File.WriteAllLines(fileName, buff.ToArray(), Encoding.UTF8);
return true;
}
Last edited: