DataGrid to CSV file - c#

I am binding a DataTable to a DataGrid, everything is working fine.
My next step is to export the DataGrid data to a CSV file, comma delimited.
What is the best/easiest way doing this with ASP.Net 3.5?

I used this Snippet to export a DataGrid To CSV. Maybe it helps:
public void OnExportGridToCSV(object sender, System.EventArgs e)
{
// Create the CSV file to which grid data will be exported.
StreamWriter sw = new StreamWriter(Server.MapPath("~/GridData.csv"), false);
// First we will write the headers.
DataTable dt = ((DataSet)grid1.DataSource).Tables[0];
int iColCount = dt.Columns.Count;
for (int i = 0; i < iColCount; i++)
{
sw.Write(dt.Columns[i]);
if (i < iColCount - 1)
{
sw.Write(",");
}
}
sw.Write(sw.NewLine);
// Now write all the rows.
foreach (DataRow dr in dt.Rows)
{
for (int i = 0; i < iColCount; i++)
{
if (!Convert.IsDBNull(dr[i]))
{
sw.Write(dr[i].ToString());
}
if (i < iColCount - 1)
{
sw.Write(System.Globalization.CultureInfo.CurrentCulture.TextInfo.ListSeparator);
}
}
sw.Write(sw.NewLine);
}
sw.Close();
}

Related

Importing text file inside of DataGridView , C#

I have a problem , on button click , dataview should get all data from text file.
I dont understand why it doesnt work .
I have another function to put data inside of the text file , that works.
Anyone can help me?
Thanks in advance
This is code of the function which should get all data and put them into the dataviewgrid when I run the program, but there is some problem , I dont get error messages at all , but its not happening .
This is code which works really good , it showing all columns and all data will be in text file
filling data
data which I got in txt file
private void dodajToolStripMenuItem_Click(object sender, EventArgs e) {
//upis u datoteku
using (TextWriter smesti = new StreamWriter("podaci.txt")) {
for (int i = 0; i < dataGridView1.Rows.Count; i++) {
if (!dataGridView1.Rows[i].IsNewRow) {
for (int j = 0; j < dataGridView1.Columns.Count; j++) {
smesti.Write(dataGridView1.Rows[i].Cells[j].Value.ToString());
if (j < dataGridView1.Columns.Count - 1) {
smesti.Write("|");
}
}
smesti.WriteLine();
}
}
}
}
private void Admin_Load(object sender, EventArgs e)
{
DataTable tabela = new DataTable();
tabela.Columns.Add("ID", typeof(int));
tabela.Columns.Add("Naziv", typeof(string));
tabela.Columns.Add("Zanr", typeof(string));
tabela.Columns.Add("Duzina", typeof(int));
tabela.Columns.Add("Granica godina: ", typeof(int));
dataGridView1.DataSource = tabela;
}
private void ucitaj()
{
DataTable tabela = new DataTable();
string[] tekst = File.ReadAllLines("podaci.txt");
string[] vrednosti;
for (int i = 0; i < tekst.Length; i++)
{
vrednosti = tekst[i].ToString().Split('|');
string[] red = new string[vrednosti.Length];
for (int j = 0; j < vrednosti.Length; j++)
{
red[j] = vrednosti[j].Trim();
}
tabela.Rows.Add(red);
}
}
private void button1_Click(object sender, EventArgs e)
{
ucitaj();
}
Try the code below to write the grid data to the file. The code simply writes each cell to the file, then it writes a Bar “|” delimiter unless the cell is the last cell on the row. We do not want a delimiter at the end of the line.
private void dodajToolStripMenuItem_Click(object sender, EventArgs e) {
//upis u datoteku
using (TextWriter smesti = new StreamWriter("podaci.txt")) {
for (int i = 0; i < dataGridView1.Rows.Count; i++) {
if (!dataGridView1.Rows[i].IsNewRow) {
for (int j = 0; j < dataGridView1.Columns.Count; j++) {
smesti.Write(dataGridView1.Rows[i].Cells[j].Value.ToString());
if (j < dataGridView1.Columns.Count - 1) {
smesti.Write("|");
}
}
smesti.WriteLine();
}
}
}
}
Then in the code that reads the file....
DataTable tabela;
private void ucitaj() {
//DataTable tabela = new DataTable();
tabela.Rows.Clear();
string[] tekst = File.ReadAllLines("podaci.txt");
string[] vrednosti;
for (int i = 0; i < tekst.Length; i++) {
vrednosti = tekst[i].ToString().Split('|');
string[] red = new string[vrednosti.Length];
for (int j = 0; j < vrednosti.Length; j++) {
red[j] = vrednosti[j].Trim();
}
tabela.Rows.Add(red);
}
dataGridView1.DataSource = tabela;
}
AND... you need to move the DataTable ... tabela to be a global variable. SO make tabela global...
DataTable tabela;
Then in the Load event, change the line...
DataTable tabela = new DataTable();
To...
tabela = new DataTable();

C# Windows Application export datatable data to .csv file

What I want is to export datatable to a .csv file.
Here is what I tried but the time it takes is too long:
string strFilePath= #"C:\myCSVfile.csv";
--
public void CreateCSVFile(DataTable dtDataTablesList, string strFilePath)
{
// Create the CSV file to which grid data will be exported.
StreamWriter sw = new StreamWriter(strFilePath, false);
//First we will write the headers.
int iColCount = dtDataTablesList.Columns.Count;
for (int i = 0; i < iColCount; i++)
{
sw.Write(dtDataTablesList.Columns[i]);
if (i < iColCount - 1)
{
sw.Write(",");
}
}
sw.Write(sw.NewLine);
// Now write all the rows.
foreach (DataRow dr in dtDataTablesList.Rows)
{
for (int i = 0; i < iColCount; i++)
{
if (!Convert.IsDBNull(dr[i]))
{
sw.Write(dr[i].ToString());
}
if (i < iColCount - 1)
{
sw.Write(",");
}
}
sw.Write(sw.NewLine);
}
sw.Close();
}
Is there some any other way to do this faster?
Thank you in advance for any suggestions.
It is now faster and this is what I did:
I counted the number of processors
Create a thread for each
Divide the rows over the threads
Have each export to their own file
Combine the files at the end
Add a nice progress-display

How to Export DataSet to notepad?

how to Export DataSet(multiple of Datatables) to a notepad. From c#
Note: NOT A SINGLE DataTable ,Multiple DataTables From DataSet;
I would suggest something simple, create a translator or download a bunch of other libraries available on the web.
you would most like go
public interfacte IExport
{
bool Export(Databale sometable);// this can also reference interface
//concrete implementation could also handle saving of file
}
then call on a concrete class to implement that value, use a Factory Patter, Dependency Injection, etc to supply the concrete type. Then you can keep adding as many converters to support as many file types as you'd like.
private void Write(System.Data.DataSet dts, string outputFilePath)
{
System.Data.DataTable dt = new System.Data.DataTable();
for (int z = 0; z < dts.Tables.Count; z++)
{
dt = dts.Tables[z];
int[] maxLengths = new int[dt.Columns.Count];
for (int i = 0; i < dt.Columns.Count; i++)
{
maxLengths[i] = dt.Columns[i].ColumnName.Length;
foreach (DataRow row in dt.Rows)
{
if (!row.IsNull(i))
{
int length = row[i].ToString().Length;
if (length > maxLengths[i])
{
maxLengths[i] = length;
}
}
}
}
using (StreamWriter sw = new StreamWriter(outputFilePath, true))
{
for (int i = 0; i < dt.Columns.Count; i++)
{
sw.Write(dt.Columns[i].ColumnName.PadRight(maxLengths[i] + 2));
}
sw.WriteLine();
foreach (DataRow row in dt.Rows)
{
for (int i = 0; i < dt.Columns.Count; i++)
{
if (!row.IsNull(i))
{
sw.Write(row[i].ToString().PadRight(maxLengths[i] + 2));
}
else
{
sw.Write(new string(' ', maxLengths[i] + 2));
}
}
sw.WriteLine();
}
sw.Close();
}
}
}

How to write a text file from a .NET DataGridView control cell values?

I have the following code that should loop through all the rows in my DataGridView, and write all their cell values to a text file.
However, it outputs all the rows, but only the first cell of each one, and not the other three cells.
string file_name = "C:\\test1.txt";
var objWriter = new System.IO.StreamWriter(file_name);
int count = dgv.Rows.Count;
for (int row = 0; row < count; row++)
{
objWriter.WriteLine(dgv.Rows[row].Cells[0].Value.ToString());
}
objWriter.Close();
for (int row = 0; row < count; row++)
{
int colCount = dgv.Rows[row].Cells.Count;
for ( int col = 0; col < colCount; col++)
{
objWriter.WriteLine(dgv.Rows[row].Cells[col].Value.ToString());
}
// record seperator could be written here.
}
Although, it would be cleaner if you used a foreach loop.
TextWriter sw = new StreamWriter(#"D:\\file11.txt");
int rowcount = dataGridViewX1.Rows.Count;
for (int i = 0; i < rowcount - 1; i++)
{
sw.WriteLine(dataGridViewX1.Rows[i].Cells[0].Value.ToString());
}
sw.Close();
MessageBox.Show("Text file was created." );

Reading data from DataGridView in C#

How can I read data from DataGridView in C#? I want to read the data appear in Table. How do I navigate through lines?
something like
for (int rows = 0; rows < dataGrid.Rows.Count; rows++)
{
for (int col= 0; col < dataGrid.Rows[rows].Cells.Count; col++)
{
string value = dataGrid.Rows[rows].Cells[col].Value.ToString();
}
}
example without using index
foreach (DataGridViewRow row in dataGrid.Rows)
{
foreach (DataGridViewCell cell in row.Cells)
{
string value = cell.Value.ToString();
}
}
If you wish, you can also use the column names instead of column numbers.
For example, if you want to read data from DataGridView on the 4. row and the "Name" column.
It provides me a better understanding for which variable I am dealing with.
dataGridView.Rows[4].Cells["Name"].Value.ToString();
Hope it helps.
string[,] myGridData = new string[dataGridView1.Rows.Count,3];
int i = 0;
foreach(DataRow row in dataGridView1.Rows)
{
myGridData[i][0] = row.Cells[0].Value.ToString();
myGridData[i][1] = row.Cells[1].Value.ToString();
myGridData[i][2] = row.Cells[2].Value.ToString();
i++;
}
Hope this helps....
Code Example : Reading data from DataGridView and storing it in an array
int[,] n = new int[3, 19];
for (int i = 0; i < (StartDataView.Rows.Count - 1); i++)
{
for (int j = 0; j < StartDataView.Columns.Count; j++)
{
if(this.StartDataView.Rows[i].Cells[j].Value.ToString() != string.Empty)
{
try
{
n[i, j] = int.Parse(this.StartDataView.Rows[i].Cells[j].Value.ToString());
}
catch (Exception Ee)
{ //get exception of "null"
MessageBox.Show(Ee.ToString());
}
}
}
}
private void HighLightGridRows()
{
Debugger.Launch();
for (int i = 0; i < dtgvAppSettings.Rows.Count; i++)
{
String key = dtgvAppSettings.Rows[i].Cells["Key"].Value.ToString();
if (key.ToLower().Contains("applicationpath") == true)
{
dtgvAppSettings.Rows[i].DefaultCellStyle.BackColor = Color.Yellow;
}
}
}

Categories

Resources