I am exporting data from a database in Sql Server to an Excel. I'm doing it in C # of Windows Forms type.
If you export the information to me, but the columns of my table do not generate them and also some fields it puts as true as it is shown in this image:
Exception from HRESULT: 0x800A03EC
pointing to this line of code:
xlWorkSheet.Cells[i, j] = miTabla.Columns[i].ColumnName.ToString();
This is the code:
private void button1_Click(object sender, EventArgs e)
{
SqlConnection cnn;
string connectionstring = null;
string sql = null;
string data = null;
int i = 1;
int j = 1;
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
xlApp = new Microsoft.Office.Interop.Excel.Application();
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
connectionstring = "server=192.168.105.150\sql2012; database=Credito; user id=sa; password=DBServ@14;";
cnn = new SqlConnection(connectionstring);
cnn.Open();
sql = "SELECT top 1 * FROM credito..cuotacredito";
SqlDataAdapter dscmd = new SqlDataAdapter(sql, cnn);
DataSet ds = new DataSet();
dscmd.Fill(ds);
DataTable miTabla = ds.Tables[0];
for (i = 1; i < miTabla.Rows.Count; i++)
{
xlWorkSheet.Cells[i, j] = miTabla.Columns[i].ColumnName.ToString();
// Recorrer las columnas de la tabla:
for (j = 1; j < miTabla.Columns.Count; j++)
{
//xlWorkSheet.Cells[i, j] = miTabla.Rows[j][i].ToString();
xlWorkSheet.Cells[i, j].Value = miTabla.Rows[j][i].ToString();
}
}
/*
for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
for (j = 0; j <= ds.Tables[0].Columns.Count - 1; j++)
{
data = ds.Tables[0].Rows[i].ItemArray[j].ToString();
data1 = ds.Tables[0].Columns[j].ToString();
xlWorkSheet.Cells[i + 2, j + 1] = data+data1;
}
} */
xlApp.Visible = true;
}