how to export datagridview data to pipe separated text using c# .net windows application?
I want to export datagridview data to psv format using c# .net windows application.
How it can be possible?
Thanks in Advance.
Ankit Agarwal
Software Engineer
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Ankit AgarwalPosted Aug 31, 2013, 7:40 AM
Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application();
// creating new WorkBook within Excel application
Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Add(Type.Missing);
// creating new Excelsheet in workbook
Microsoft.Office.Interop.Excel._Worksheet worksheet = null;
// see the excel sheet behind the program
app.Visible = true;
// get the reference of first sheet. By default its name is Sheet1.
// store its reference to worksheet
worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Sheets["Sheet1"];
worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.ActiveSheet;
// changing the name of active sheet
worksheet.Name = "UUSProducts";
// storing header part in Excel
for (int i = 1; i < dataGridView1.Columns.Count + 1; i++)
{
worksheet.Cells[1, i] = dataGridView1.Columns[i - 1].HeaderText;
}
// storing Each row and column value to excel sheet
for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
{
for (int j = 0; j < dataGridView1.Columns.Count; j++)
{
worksheet.Cells[i + 2, j + 1] = dataGridView1.Rows[i].Cells[j].Value.ToString();
}
}
// save the application
workbook.SaveAs("c:\\UUSProducts.xls", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
// Exit from the application
app.Quit();
but this code successfully run but when i importing this excel file so getting exception: "External table is not in the expected format" i am using .xls format for excel.
So, how can we remove this exception?
Please help me.
Ankit Agarwal
Softeware Engineer
Posted Aug 30, 2013, 3:33 AM
Note : The table variable should be your data source of the gridview control. Or you can use gridview.DataSource(with type casting).
string temp = string.Empty;
foreach (DataColumn colx in table.Columns)
{
temp = temp + colx.ColumnName + "|";
}
temp = temp + Environment.NewLine;
foreach (DataRow item in table.Rows)
{
foreach(string str in item.ItemArray)
{
temp = temp + str + "|";
}
temp = temp + Environment.NewLine;
}
System.IO.File.AppendAllText(@"c:\temp.psv",temp);
Posted Aug 30, 2013, 3:31 AM
Ankit AgarwalPosted Aug 30, 2013, 3:30 AM
Posted Aug 30, 2013, 3:21 AM