Reputation: 13
The problem is that I want what I did to my previous program that saved the data of a database in excel, now it does it in parameters separated by commas. I have searched for examples here in StackOverflow and I have had good results but I still can not get my code to do what I need. I leave my complete code.
I leave the reference code but what I need help is in private void SaveToCSV()
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using IniFile;
using Microsoft.Office.Interop.Excel;
using SGP_Base.Classes;
using Application = Microsoft.Office.Interop.Excel.Application;
namespace MES_SERVER
{
public partial class FrmSerialAllResults : Form
{
public FrmSerialAllResults()
{
InitializeComponent();
LoadDatas();
CargarPermisos();
}
private void LoadDatas()
{
dataGridViewResults.Rows.Clear();
serial_resultados serialResultados = new serial_resultados();
serialResultados.SeleccionarDatos("");
DatagridView(serialResultados, "No existen Resultados", serialResultados.Filas().Count - 50);
}
private void CargarPermisos()
{
Permisos permisos = new Permisos();
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("@objetos1", "Exportar a excel");
permisos.SeleccionarDatos("objetos =@objetos1", parameters);
buttonExportExcel.Enabled= Convert.ToBoolean(int.Parse(permisos.Filas()[0].Celda(Global.level).ToString()));
}
private void DatagridView(serial_resultados serialResultados, string mensaje, int total)
{
if (serialResultados.TieneFilas())
{
//int inicio = serialResultados.Filas().Count - 50;
int inicio = total;
int k = 0;
foreach (Fila fila in serialResultados.Filas())
{
if (k >= inicio)
{
dataGridViewResults.Rows.Add(fila.Celda("id"), fila.Celda("fecha"), fila.Celda("serial"),
fila.Celda("estacion"), " ", fila.Celda("status"),
fila.Celda("distancia"), fila.Celda("fuerza"), fila.Celda("vacio"), fila.Celda("presion"),
fila.Celda("tiempociclo"),
fila.Celda("total_ensamblados"), fila.Celda("ensamblado_a"));
}
k++;
}
for (int i = 0; i < dataGridViewResults.Rows.Count; i++)
{
if (int.Parse(dataGridViewResults["Status", i].Value.ToString()) == 0)
{
dataGridViewResults["Status", i].Value = "NOK";
dataGridViewResults["Status", i].Style.BackColor = Color.OrangeRed;
dataGridViewResults["Status", i].Style.ForeColor = Color.White;
}
else
{
dataGridViewResults["Status", i].Value = "OK";
dataGridViewResults["Status", i].Style.BackColor = Color.LimeGreen;
}
string station = dataGridViewResults["Station", i].Value.ToString();
string newName =ObtenerNombre(station);
dataGridViewResults["nombre", i].Value = newName;
}
toolStripStatusLabelCounRows.Text = "Filas Totales: " + serialResultados.Filas().Count.ToString();
}
else
{
MessageBox.Show(mensaje, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private string ObtenerNombre(string estation)
{
string numberstation = estation.Replace("E", "");
Ini ini = new Ini(Global.PathFileIni);
string name =ini.IniReadValue("Maquina" + numberstation, "Name");
return name;
}
private string ObtenerEstacion(string name)
{
string pathFile = Global.PathFileIni;
if (File.Exists(pathFile))
{
Ini ini = new Ini(pathFile);
string valor = ini.IniReadValue("NumberTotalMachine", "Total");
if (valor != "")
{
int total = int.Parse(valor);
for (int i = 1; i <= total; i++)
{
if (ini.IniReadValue("Maquina" + i, "Name") == name)
{
return "E" + i;
}
}
}
}
return "";
}
private void buttonExportExcel_Click(object sender, EventArgs e)
{
try
{
//SaveExcel();
SaveToCSV();
}
catch{}
}
private void SaveToCSV()
{
string dataDay = DateTime.Today.ToString().Replace("/", "");
dataDay = dataDay.Replace(":", "");
dataDay = dataDay.Replace(" ", "");
DataGridView dataGridViewResults = new DataGridView();
SaveFileDialog sfd = new SaveFileDialog();
string filename = "";
string filter = "CSV file (*.csv)|*.csv| All Files (*.*)|*.*";
sfd.FileName = "Registro_" + dataDay + ".csv";
sfd.Filter = filter;
if (sfd.ShowDialog() == DialogResult.OK)
{
MessageBox.Show("Se estan exportando sus datos, se notificara cuando este listo");
if (File.Exists(filename))
{
try
{
File.Delete(filename);
}
catch (IOException ex)
{
MessageBox.Show("No fue posible escribir los datos en el disco" + ex.Message);
}
}
int columnCount = dataGridViewResults.ColumnCount;
string columnNames = "";
string[] output = new string[dataGridViewResults.RowCount + 1];
for (int i = 1; (i - 1) < dataGridViewResults.RowCount; i++)
{
columnNames += dataGridViewResults.Columns[i].Name.ToString() + ",";
}
output[0] += columnNames;
for (int i = 1; (i - 1) < dataGridViewResults.RowCount; i++)
{
for (int j = 0; j < columnCount; j++)
{
output[i] += dataGridViewResults.Rows[i - 1].Cells[j].Value.ToString() + "/n";
}
}
System.IO.File.WriteAllLines(sfd.FileName, output, System.Text.Encoding.UTF8);
MessageBox.Show("El archivo esta listo para su uso");
}
}
/* private void SaveExcel()
{
string dataDay = DateTime.Today.ToString().Replace("/", "");
dataDay = dataDay.Replace(":", "");
dataDay = dataDay.Replace(" ", "");
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "Excel Documents(*.xls)|*.xls";
saveFileDialog.FileName = "Registro_" + dataDay + ".xls";
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
object Value = System.Reflection.Missing.Value;
Application excelApplication = new Application();
excelApplication.Visible = true;
Workbook workbook = excelApplication.Workbooks.Add(Value);
Worksheet worksheet = (Worksheet)workbook.Sheets["Sheet1"];
worksheet = (Worksheet)workbook.ActiveSheet;
worksheet.Cells[1, 1] = "Fecha";
worksheet.Cells[1, 2] = "Serial";
worksheet.Cells[1, 3] = "Estacion";
worksheet.Cells[1, 4] = "Nombre";
worksheet.Cells[1, 5] = "Estatus";
worksheet.Cells[1, 6] = "Distancia";
worksheet.Cells[1, 7] = "Fuerza";
worksheet.Cells[1, 8] = "Vacio";
worksheet.Cells[1, 9] = "Presion";
worksheet.Cells[1, 10] = "Tiempo de ciclo";
worksheet.Cells[1, 11] = "Total ensamblados";
worksheet.Cells[1, 12] = "Ensamblado a";
int FilasCount = dataGridViewResults.RowCount;
int k = 2;
for (int i = 0; i < FilasCount; i++)
{
worksheet.Cells[k, 1] = dataGridViewResults["fecha", i].Value.ToString();
worksheet.Cells[k, 2] = dataGridViewResults["serial", i].Value.ToString();
worksheet.Cells[k, 3] = dataGridViewResults["Station", i].Value.ToString();
worksheet.Cells[k, 4] = dataGridViewResults["nombre", i].Value.ToString();
worksheet.Cells[k, 5] = dataGridViewResults["Status", i].Value.ToString();
worksheet.Cells[k, 6] = dataGridViewResults["distancia", i].Value.ToString();
worksheet.Cells[k, 7] = dataGridViewResults["fuerza", i].Value.ToString();
worksheet.Cells[k, 8] = dataGridViewResults["vacio", i].Value.ToString();
worksheet.Cells[k, 9] = dataGridViewResults["presion", i].Value.ToString();
worksheet.Cells[k, 10] = dataGridViewResults["tiempociclo", i].Value.ToString();
worksheet.Cells[k, 11] = dataGridViewResults["totalensambles", i].Value.ToString();
worksheet.Cells[k, 12] = dataGridViewResults["ensamblado_a", i].Value.ToString();
k++;
}
workbook.SaveAs(saveFileDialog.FileName, XlFileFormat.xlWorkbookNormal, Value, Value, Value, Value, XlSaveAsAccessMode.xlExclusive, Value, Value, Value, Value, Value);
workbook.Close(true, Value, Value);
excelApplication.Quit();
}
} */
private void textBoxEstación_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == 13)
{
if (textBoxEstación.Text != "")
SearchEstacion();
else
LoadDatas();
textBoxEstación.Text = "";
}
}
private void SearchEstacion()
{
string estacion = ObtenerEstacion(textBoxEstación.Text);
if (estacion == "")
estacion = textBoxEstación.Text;
dataGridViewResults.Rows.Clear();
serial_resultados serialResultados = new serial_resultados();
serialResultados.SeleccionarDatos("estacion='" + estacion + "'");
DatagridView(serialResultados, "No existen datos para " + textBoxEstación.Text,0);
}
private void textBoxSerial_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == 13)
{
if (textBoxSerial.Text != "")
SearchSerial();
else
LoadDatas();
textBoxSerial.Text = "";
}
}
private void SearchSerial()
{
dataGridViewResults.Rows.Clear();
serial_resultados serialResultados = new serial_resultados();
serialResultados.SeleccionarDatos("serial LIKE '%" + textBoxSerial.Text + "%'");
DatagridView(serialResultados, "No existen datos para " + textBoxSerial.Text, 0);
}
private void textBoxEnsamble_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == 13)
{
if (textBoxEnsamble.Text != "")
SearchEnsamble();
else
LoadDatas();
textBoxEnsamble.Text = "";
}
}
private void SearchEnsamble()
{
dataGridViewResults.Rows.Clear();
serial_resultados serialResultados = new serial_resultados();
serialResultados.SeleccionarDatos("ensamblado_a LIKE '%" + textBoxEnsamble.Text + "%'");
DatagridView(serialResultados, "No existen datos para " + textBoxEnsamble.Text,0);
}
private void buttonReload_Click(object sender, EventArgs e)
{
LoadDatas();
}
private void dateTimePicker1_CloseUp(object sender, EventArgs e)
{
SearchDateTime();
}
private void SearchDateTime()
{
string Formato = "yyyy-MM-dd";
string Date = dateTimePicker1.Value.ToString(Formato);
dataGridViewResults.Rows.Clear();
serial_resultados serialResultados = new serial_resultados();
serialResultados.SeleccionarDatos("fecha LIKE '%" + Date + "%'");
DatagridView(serialResultados, "No existen datos de la fecha " + Date,0);
}
private void dataGridViewResults_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
}
}
Upvotes: 1
Views: 1974
Reputation: 9469
As Steve pointed out, the posted code is trying to print a DataGridView
that has no columns or rows. Specifically in the SaveToCSV
method on line 4 there is the following line of code…
DataGridView dataGridViewResults = new DataGridView();
This creates a NEW DataGridView
with no columns or rows. Following the code… the grid is never given columns or rows, If you trace the code you will notice it never enters any of the for
loops. Therefore, an empty file is created,
There are many ways to write a DataGridView
’s cells to a csv file. Often it may be easier if the grid has a data source and use it instead of looping through the grid. However, if you wanted to write the grids contents to a csv file as you describe, the code below may help.
To break the problem down, a helper method GetCommaDelimitedRow
takes a DataGridView
and an int
for a row index and returns a comma delimited string from the grid at the given row index. If the row index is less than zero (0), then a comma-delimited string from the grids column headers is returned. This method uses a StringBuilder
to append the “delimiter” ‘,’ after each value except for the last column where a trailing comma would be undesirable.
The PrintGridToCSV
method takes a DataGridView
and a string
path/file name to write to. A StringBuilder
is used in place of the string array such that each line in the string builder would be a comma delimited row from the grid. First a check to make sure the grid is not null, has at least one (1) column and at least one (1) row. If there are columns and rows, add the column headers row using the helper method with -1 as the row index. Then loop through the rows and using the helper method adding those strings to the string builder. Finally write the string builder to file using the WriteAllText
method. I hope this helps.
private string GetCommaDelimitedRow(DataGridView grid, int rowIndex) {
StringBuilder sb = new StringBuilder();
for (int curCol = 0; curCol < grid.Columns.Count; curCol++) {
if (rowIndex < 0)
sb.Append(grid.Columns[curCol].Name);
else {
if (grid.Rows[rowIndex].Cells[curCol].Value != null) {
sb.Append(grid.Rows[rowIndex].Cells[curCol].Value.ToString());
}
else {
sb.Append("");
}
}
// if this col is not the last column... add a delimiter ','
if (curCol < grid.Columns.Count - 1)
sb.Append(",");
}
return sb.ToString();
}
PrintGridToCSV method
private void PrintGridToCSV(DataGridView grid, string fileName) {
if (grid != null && grid.Columns.Count > 0 && grid.Rows.Count > 0) {
StringBuilder sb = new StringBuilder();
sb.AppendLine(GetCommaDelimitedRow(grid, -1)); // <- add column headers row
for (int i = 0; i < grid.Rows.Count; i++) {
if (!grid.Rows[i].IsNewRow)
sb.AppendLine(GetCommaDelimitedRow(grid, i)); // <- add row data
}
try {
File.WriteAllText(fileName, sb.ToString(), Encoding.UTF8);
}
catch (Exception e) {
MessageBox.Show("File write error: " + e.Message);
}
}
else
MessageBox.Show("Grid is null... has no columns or has no rows or both!");
}
private void button1_Click(object sender, EventArgs e) {
PrintGridToCSV(dataGridView1, @"D:\Test\_MyCSVFile.csv");
}
Upvotes: 1