I'm writing a program to pull data from an SQL database and input it into Excel. I have it all working, except that I noticed the rows I have returned in Excel do not match what I see in SQL. The last row is consistently trimmed when filling the DataTable object.
Info: Visual Studio 2015, SQL Server 11.0.5058.
I have tracked down the problem to how I am retrieving the SQL data in the below method. I put in a check after going through this method to output how many rows were returned, and it's consistently one less than I should have (queries are identical). I think it's an indexing issue but I can't see how, given the simplicity of the below method. I can't figure out why the last row is being trimmed out when put into the data table.
private static DataTable PullData(string connstr, string query)
{
// Creating connection to SQL server
SqlConnection conn = new SqlConnection(connstr);
SqlCommand cmd = new SqlCommand(query, conn);
conn.Open();
DataTable dataTable = new DataTable();
// create data adapter
using (SqlDataAdapter da = new SqlDataAdapter(query, conn))
{
da.SelectCommand.CommandTimeout = 3600;
// query database and return the result to your datatable
da.Fill(dataTable);
da.Dispose();
}
conn.Close();
return dataTable;
}
****EDIT****: Thank you Tim for helping me track down the issue.. Turns out it was not in my DataTable but in my Excel Range object. There must be differences between how indexing works in Excel/SQL/C# from the last time I used this method of writing data to Excel. Since Excel technically sees Row 1 as the column header, I had to add 1 to the number of rows for the Excel Range object in order for it to accept the correct total number:
Excel.Range range = wsheet.Range["A2", String.Format("{0}{1}", GetExcelColumnName(columns), rows+1)];