Click here to Skip to main content
15,886,769 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Dear All,

A B
1 Rm 23
2 hg e3
3 23 sdf
4 23 dsf
5 23 32

i want to save the .csv file header name and row number, how i achieve this c#.
Please Help me.

Thanks Advance.
Posted
Comments
StM0n 14-Aug-14 1:14am    
Could you please clearify the structure of your data by using the code tag? I'm not quite sure, what's your header and what's your data...

1 solution

Dear Member 10868354,

I am answering thing assuming you having one DataTable, that you want to convert into CSV File.
In DataTable we having COLUMN HEADER(COLUMN NAME) and Data Rows.


C#
public static string CSVGenerate(DataTable table)
    {
        var CSVresult = new StringBuilder();
        for (int i = 0; i < table.Columns.Count; i++)
        {
            CSVresult.Append(table.Columns[i].ColumnName);
            CSVresult.Append(i == table.Columns.Count - 1 ? "\n" : ",");
        }

        foreach (DataRow row in table.Rows)
        {
            for (int i = 0; i < table.Columns.Count; i++)
            {
                CSVresult.Append(row[i].ToString());
                CSVresult.Append(i == table.Columns.Count - 1 ? "\n" : ",");
            }
        }

        return CSVresult.ToString();
}


C#
table
is my datatable variable passed to CSVGenerate method.

Please, Try & Check this.If, you having fruther any query feel free to contact.

If its your answer don't forget to mark as answer.

Thanking You,
Manoj Kalla
 
Share this answer
 
Comments
Member 10868354 14-Aug-14 5:39am    
Thanks For Your Reply. Kalla
Member 10868354 14-Aug-14 5:40am    
I want to insert .csv data into database using C# , include header and left side row number. Now I Do like this see below my coding . I'm expecting Your Reply


protected void btCSVUpload_Click(object sender, EventArgs e)
{



if (FileUploadControl.HasFile)
{
FileInfo fileInfo = new FileInfo(FileUploadControl.PostedFile.FileName);
if (fileInfo.Name.Contains(".csv"))
{

string fileName = fileInfo.Name.Replace(".csv", "").ToString();
string csvFilePath = Server.MapPath("UploadedCSVFiles") + "\\" + fileInfo.Name;

//Save the CSV file in the Server inside 'MyCSVFolder'
FileUploadControl.SaveAs(csvFilePath);

//Fetch the location of CSV file
string filePath = Server.MapPath("UploadedCSVFiles") + "\\";
string strSql = "SELECT * FROM [" + fileInfo.Name + "]";
string strCSVConnString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";" + "Extended Properties='text;HDR=YES;'";

// load the data from CSV to DataTable

OleDbDataAdapter adapter = new OleDbDataAdapter(strSql, strCSVConnString);
DataTable dtCSV = new DataTable();
DataTable dtSchema = new DataTable();
adapter.FillSchema(dtCSV, SchemaType.Mapped);
adapter.Fill(dtCSV);
if (dtCSV.Rows.Count > 0)
{

//CreateDatabaseTable(dtCSV, fileName);
//Label2.Text = string.Format("The table ({0}) has been successfully created to the database.", fileName);
string fileFullPath = filePath + fileInfo.Name;
LoadDataToDatabase(fileName, fileFullPath, ",");
if (DuplicateCnt == 0)
{
Label1.Text = string.Format("({0}) records has been loaded to the table {1}.", dtCSV.Rows.Count, fileName);
}
}
else
{
lbStatus.Text = "File is empty.";
}
}
else
{
lbStatus.Text = "Unable to recognize file.";
}
}
}




private void LoadDataToDatabase(string tableName, string fileFullPath, string delimeter)
{
string sqlQuery = string.Empty;
StringBuilder sb = new StringBuilder();
//sb.AppendFormat(string.Format("BULK INSERT {0} ", tableName));
sb.AppendFormat(string.Format("BULK INSERT HdbRpt"));
sb.AppendFormat(string.Format(" FROM '{0}'", fileFullPath));
sb.AppendFormat(string.Format(" WITH ( FIELDTERMINATOR = '{0}' , ROWTERMINATOR = '\n' )", delimeter));

sqlQuery = sb.ToString();

using (SqlConnection sqlConn = new SqlConnection(GetConnectionString()))
{
try
{
DuplicateCnt = 0;
sqlConn.Open();
SqlCommand sqlCmd = new SqlCommand(sqlQuery, sqlConn);
sqlCmd.ExecuteNonQuery();
sqlConn.Close();
}
catch { DuplicateCnt = 1; ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('This Data is are alreaddy inserted')", true); }
}
}

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900