I'm using C# and EPPlus to import .csv data into a workbook. My only issue is that after the import into Excel, I am losing trailing zeroes on the data.
For example:
in the .CSV file, the data is this: 1250.80
in the .xlsx file, the data ends up being 1250.8
Seems minor but I need this to compare workbook to workbook and not see all of these diffs.
Here is the read routine
string[] csvInputfile = File.ReadAllLines(filePathName);
Here is how I am trying to put double quotes around the data
for (int idx = 0; idx < csvInputfile.Length; idx++)
{
csvInputfile[idx] = csvInputfile[idx].Replace(",", ",\"");
}
Here I am writing the contents to the Excel instance
for (int i = 0; i < csvInputfile.Length; i++)
{
ExcelWorksheet curWorksheet = excelPackage.Workbook.Worksheets.Add(csvInputfile[outerLoopCnt]);
for (int j = 0; j < csvInputfile.Length; j++)
{
innerLoopCnt++;
curWorksheet.Cells[j + 1, 1, j + 1, 100].Style.Numberformat.Format = "#";
curWorksheet.Cells[j + 1, 1].LoadFromText(csvInputfile[innerLoopCnt], format);
if (csvInputfile[innerLoopCnt + 1] == "")
{
outerLoopCnt = innerLoopCnt + 2;
innerLoopCnt += 2;
break;
}
}
if (innerLoopCnt == csvInputfile.Length)
{
break;
}
}
Here I save the file:
excelPackage.SaveAs(file);
This is the general idea and its not working very well. This is a crude approach but I'm not sure how else to make this work, I would appreciate any help
I'm currently attempting to use datagridview for the first time, I have managed to do many things with it so far (such as importing text files) however, I have trouble when attempting to save the datagridview's contents to a text file.
The output I'm currently getting is:
0,
Cat,
Yes,
10,
20,
30,
40,
50,
1,
Dog,
No,
10,
20,
30,
40,
50,
I want the export to look like this:
0, Cat, Yes, 10, 20, 30, 40, 50
1, Dog, No, 10, 20, 30, 40, 50
etc.
This is the code I'm currently using:
using (TextWriter tw = new StreamWriter("example.txt"))
{
for(int i = 0; i < dataGridView1.Rows.Count - 1; i++)
{
for(int j = 0; j < dataGridView1.Columns.Count; j++)
{
tw.WriteLine($"{dataGridView1.Rows[i].Cells[j].Value.ToString()},");
}
}
}
Anyone here able to help me with this issue? Thank you!
Try the following changes tw.Write() insted of tw.WriteLine():
using (TextWriter tw = new StreamWriter("example.txt"))
{
for(int i = 0; i < dataGridView1.Rows.Count - 1; i++)
{
for(int j = 0; j < dataGridView1.Columns.Count; j++)
{
tw.Write($"{dataGridView1.Rows[i].Cells[j].Value.ToString()}");
if(!j == dataGridView1.Columns.Count - 1)
{
tw.Write(",");
}
}
tw.WriteLine();
}
}
So, DGV to Text file? This is how I do it.
private void button1_Click(object sender, EventArgs e)
{
//This line of code creates a text file for the data export.
System.IO.StreamWriter file = new System.IO.StreamWriter(#"C:\\your_path_here\\sample.txt");
try
{
string sLine = "";
//This for loop loops through each row in the table
for (int r = 0; r <= dataGridView1.Rows.Count - 1; r++)
{
//This for loop loops through each column, and the row number
//is passed from the for loop above.
for (int c = 0; c <= dataGridView1.Columns.Count - 1; c++)
{
sLine = sLine + dataGridView1.Rows[r].Cells[c].Value;
if (c != dataGridView1.Columns.Count - 1)
{
//A comma is added as a text delimiter in order
//to separate each field in the text file.
//You can choose another character as a delimiter.
sLine = sLine + ",";
}
}
//The exported text is written to the text file, one line at a time.
file.WriteLine(sLine);
sLine = "";
}
file.Close();
System.Windows.Forms.MessageBox.Show("Export Complete.", "Program Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (System.Exception err)
{
System.Windows.Forms.MessageBox.Show(err.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
file.Close();
}
}
Use tw.Write() instead of tw.WriteLine() until you are finished with all but the last column for the row, then you tw.WriteLine() on the last column data to end the line.
I don't work in C#, but often use these forums as a reference. I develop interfaces for industrial applications. Anyway, the simplest way to do this is through the clipboard. Use the SelectAll() method on your DGV, Throw that DGV data into the Clipboard with the Clipboard.SetDataObject() method, use the File.WriteAllText(), and Clipboard.GetText() methods to write the clipboard text to a file. My code is below. You will notice I have to write out everything from it's namespace so I apologize for it not being exactly how C# is. Note: If you want to make a csv file, DGVs view cell breaks as horizontal tabs (ascii 9). You can do a replace() method for commas. Note: DGV.ClearSelection() is a nice way to finish it off. Note: you may have to enable ClipboardCopyMode on your DGV.
DataGridView1.SelectAll();
System.Windows.Forms.Clipboard.SetDataObject(DataGridView1.GetClipboardContent());
System.IO.File.WriteAllText("File.txt",System.Windows.Forms.Clipboard.GetText());
With the following code you can save and restore the content of every dataGridView.
How to do it:
string sContent = "";
private void btnSaveDataGridViewContent_Click(object sender, EventArgs e)
{
sContent = ReadStringFromDataGridView(ref dataGridView1);
[Write sContent to File/Database/Whatever]
}
private void btnRestoreDataGridViewContent_Click(object sender, EventArgs e)
{
[Read sContent from File/Database/Whatever]
WriteStringToDataGridView(ref dataGridView1, sContent);
}
Helper functions:
string ReadStringFromDataGridView(ref DataGridView MyDataGridView)
{
string sContent = "";
for (int row = 0; row<MyDataGridView.RowCount; row++)
{
if (row > 0) sContent += "\r";
for (int col = 0; col<MyDataGridView.ColumnCount; col++)
{
if (col > 0) sContent += ";";
sContent += MyDataGridView[col, row].Value;
}
}
return sContent;
}
void WriteStringToDataGridView(ref DataGridView MyDataGridView, string sContent)
{
MyDataGridView.Rows.Clear();
string[] Rows = sContent.Split("\r".ToCharArray());
for (int row=0; row<Rows.Length; row++)
{
MyDataGridView.RowCount = Rows.Length;
string[] Cols = Rows[row].Split(";".ToCharArray());
for (int col=0; col<Cols.Length; col++)
{
MyDataGridView[col, row].Value = Cols[col];
}
}
}
string file = "C:\\Users\\Sangeeth\\Desktop\\Excel.txt";
using (TextWriter tw = new StreamWriter(file))
{
int i, j = 0;
for(i = 0; i < dataGridView1.Rows.Count -1; i++)
{
for (j = 0; j < dataGridView1.Columns.Count; j++)
{
tw.Write($"{dataGridView1.Rows[i].Cells[j].Value.ToString()}");
tw.Write(",");
}
tw.WriteLine(" ");
}
}
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();
}
}
}
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." );
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();
}