Can any find my mistake while dumping the data into excel? - c#-4.0

I have a two table's ,where i have to dump the info into the Excel.I have used the follwing code.But am getting the Error "Index out of Bound".
public void ConvertToTable()
{
DataSet ds = new DataSet();
DataTable dt1 = new DataTable();
DataTable dt2 = new DataTable();
dt1 = ExportToExcel.ToDataTable<CMInfo>(CMInfo);
dt2 = ExportToExcel.ToDataTable<RefMInfo>(REFMINFO);
dt1.TableName = "Changed Method Information";
dt2.TableName = "Referenced Method Information";
ds.Tables.Add(dt1);
ds.Tables.Add(dt2);
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet[] xlWorkSheet = new Excel.Worksheet[ds.Tables.Count];
int Sheet_Count = 0;
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.Application();
xlApp.SheetsInNewWorkbook = ds.Tables.Count;
xlWorkBook = xlApp.Workbooks.Add(misValue);
foreach (DataTable dt in ds.Tables)
{
if (Sheet_Count < ds.Tables.Count)
{
xlWorkSheet[Sheet_Count] = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(Sheet_Count + 1);
xlWorkSheet[Sheet_Count].Name = dt.TableName;
int iCol = 0;
foreach (DataColumn c in dt.Columns)
{
iCol++;
xlWorkSheet[Sheet_Count].Cells[1, iCol] = c.ColumnName;
xlWorkSheet[Sheet_Count].Cells[1, iCol].Font.Bold = true;
}
// For each row of data
int iRow = 0;
foreach (DataRow r in dt.Rows)
{
iRow++;
// Add each row's cell data...
iCol = 0;
foreach (DataColumn c in dt.Columns)
{
iCol++;
xlWorkSheet[Sheet_Count].Cells[iRow + 1, iCol] = r[c.ColumnName];
xlWorkSheet[Sheet_Count].Cells.ColumnWidth = (xlWorkSheet[Sheet_Count].Cells[iRow + 1, iCol].Count() * 50);
}
}
Sheet_Count++;
}
}
xlWorkBook.SaveAs("ReferenceMethodInfo.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
Marshal.ReleaseComObject(xlWorkSheet[Sheet_Count]);
Marshal.ReleaseComObject(xlWorkBook);
Marshal.ReleaseComObject(xlApp);
ds.Clear();
System.Windows.Forms.MessageBox.Show("Exported Completed");
}
//This Code for Converting the List into DataTable
public static class ExportToExcel
{
// remove "this" if not on C# 3.0 / .NET 3.5
public static DataTable ToDataTable<T>(this IList<T> data)
{
PropertyDescriptorCollection props =
TypeDescriptor.GetProperties(typeof(T));
DataTable table = new DataTable();
for (int i = 0; i < props.Count; i++)
{
PropertyDescriptor prop = props[i];
table.Columns.Add(prop.Name, prop.PropertyType);
}
object[] values = new object[props.Count];
foreach (T item in data)
{
for (int i = 0; i < values.Length; i++)
{
values[i] = props[i].GetValue(item);
}
table.Rows.Add(values);
}
return table;
}
}

Difficult to say wexactly what causes the error without knowing which function or indeed which line causes the error.
I'll admit that I've never exported data to excel, and so don't know if cells are indexed on zero or from 1.
I am concerned that you initialise iRow and iCol to zero (0) and yet you increment them (to 1) before use.

Related

C#: OpenXML cannot get columns name print into excel file

This is a console application trying to print data from datatable to excel file using open XML lib. I have also provided datatable code for reference.
class ProgramCheck
{
private static void Main()
{
SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Create(#"C:\Users\nilam\Desktop\Work\project\GeneratedExcel.xlsx", SpreadsheetDocumentType.Workbook);
WorkbookPart workbookPart = spreadsheetDocument.AddWorkbookPart();
workbookPart.Workbook = new Workbook();
WorksheetPart worksheetPart = workbookPart.AddNewPart<WorksheetPart>();
worksheetPart.Worksheet = new Worksheet(new SheetData());
Sheets sheets = spreadsheetDocument.WorkbookPart.Workbook.AppendChild<Sheets>(new Sheets());
Sheet sheet = new Sheet()
{
Id = workbookPart.GetIdOfPart(worksheetPart),
SheetId = 1,
Name = "TestSheet2"
};
sheets.Append(sheet);
SheetData sheetData = worksheetPart.Worksheet.GetFirstChild<SheetData>();
DataTable dt = Data.SampleData();
foreach (DataRow item in dt.Rows)
{
Row row = new Row();
for (int i = 0; i < item.ItemArray.Length; i++)
{
foreach (DataColumn itemCol in dt.Columns)
{
Columns col = new Columns();
Cell cell1 = new Cell()
{
CellValue = new CellValue(item[i].ToString()),
DataType = CellValues.String
};
col.Append(cell1);
Cell cell = new Cell()
{
CellValue = new CellValue(item[i].ToString()),
DataType = CellValues.String
};
row.Append(cell);
}
}
sheetData.Append(row);
}
workbookPart.Workbook.Save();
spreadsheetDocument.Close();
}
}
Code for row works fine, but when I try to loop through columns for heading, it does not append anything. I am using openXML to get data from the data table and output it into an excel file.
This is datatable (data.cs)
class Data
{
public static DataTable SampleData()
{
System.Data.DataTable dt = new System.Data.DataTable();
dt.Columns.Add("ID");
dt.Columns.Add("Name");
dt.Columns.Add("Salary");
dt.Rows.Add("01", "Anis", "1000");
dt.Rows.Add("02", "AK", "2000");
dt.Rows.Add("03", "Mak", "3000");
return dt;
}
}
I have looked at the documentation of openXML but could not find anything so far.
[![enter image description here][1]][1]
enter code here
[1]: https://i.stack.imgur.com/EaPLh.png
I solved this...this is for someone who needs help. This code can be more refined you are welcome to do so and paste it.
SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Create(#"C:\Users\nilam\Desktop\Work\project\GeneratedExcel.xlsx", SpreadsheetDocumentType.Workbook);
WorkbookPart workbookPart = spreadsheetDocument.AddWorkbookPart();
workbookPart.Workbook = new Workbook();
WorksheetPart worksheetPart = workbookPart.AddNewPart<WorksheetPart>();
worksheetPart.Worksheet = new Worksheet(new SheetData());
Sheets sheets = spreadsheetDocument.WorkbookPart.Workbook.AppendChild<Sheets>(new Sheets());
Sheet sheet = new Sheet()
{
Id = workbookPart.GetIdOfPart(worksheetPart),
SheetId = 1,
Name = "TestSheet2"
};
sheets.Append(sheet);
SheetData sheetData = worksheetPart.Worksheet.GetFirstChild<SheetData>();
DataTable dt = Data.SampleData();
//this is for Columns heading
Row rowHeading = new Row();
for (int j = 0; j < dt.Columns.Count; j++)
{
Cell cell1 = new Cell()
{
CellValue = new CellValue(dt.Columns[j].ColumnName.ToString()),
DataType = CellValues.String
};
rowHeading.Append(cell1);
}
sheetData.Append(rowHeading);
//this is for row content
foreach (DataRow item in dt.Rows)
{
Row row = new Row();
for (int i = 0; i < item.ItemArray.Length; i++)
{
Cell cell = new Cell()
{
CellValue = new CellValue(item[i].ToString()),
DataType = CellValues.String
};
row.Append(cell);
}
sheetData.Append(row);
}
workbookPart.Workbook.Save();
spreadsheetDocument.Close();
}

The best overloaded method match for 'double.TryParse(string, out double)' has some invalid argument

I have a excel file which have diff values for diff columns. Now I just collect data from my code :
Microsoft.Office.Interop.Excel.Application excelApp1 = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook workbook1 = excelApp.Workbooks.Open(txtcd.Text);
Microsoft.Office.Interop.Excel.Worksheet worksheet1 = (Microsoft.Office.Interop.Excel.Worksheet)workbook1.Worksheets[1];
Microsoft.Office.Interop.Excel.Range rangeSelection1 = worksheet1.Columns[1];
int breakCount1 = 0;
foreach (Microsoft.Office.Interop.Excel.Range row in rangeSelection1.Rows)
{
if (breakCount1 > 20)
{
break;
}
if (row.Row > 9)
{
Microsoft.Office.Interop.Excel.Range cell = (Microsoft.Office.Interop.Excel.Range)row.Cells[3, 1];
if (cell.Value2 != null)
{
breakCount1 = 0;
string Treadcode = cell.Value2;
Microsoft.Office.Interop.Excel.Range NetBalance = (Microsoft.Office.Interop.Excel.Range)row.Cells[3, 8];
double netbalance = 0.0;
try
{
netbalance = double.TryParse(NetBalance.Value2, out netbalance);
}
catch
{
netbalance = 0.0;
}
ds2.Tables[0].Rows.Add(Treadcode,netbalance);
}
else
{
breakCount1++;
}
}
}
here is my excel screen :
here I can't get NetBalance column data. I don't understand what's going wrong here...

reading Excel with ClosedXML

What would be the most efficient way to read an entire Excel file using ClosedXML and returning List<List<object>> ?
This somehow doesn't give me data. I get empty lists.
var wb = new XLWorkbook(finalFilePath);
var ws = wb.Worksheets.First();
var range = ws.RangeUsed();
var colCount = range.ColumnCount();
var rowCount = range.RowCount();
var i = 1;
var j = 1;
List<List<object>> data = new List<List<object>>();
while (i < rowCount + 1)
{
List<object> row = new List<object>();
while (j < colCount + 1)
{
row.Add(ws.Cell(i, j).Value);
j++;
}
data.Add(row);
i++;
}
This gets the job done:
Dictionary<Tuple<int, int>, object> data = new Dictionary<Tuple<int, int>, object>();
using (XLWorkbook wb = new XLWorkbook(filePath))
{
var ws = wb.Worksheets.First();
var range = ws.RangeUsed();
for (int i = 1; i < range.RowCount() + 1; i++)
{
for (int j = 1; j < range.ColumnCount() + 1; j++)
{
data.Add(new Tuple<int, int>(i,j), ws.Cell(i,j).Value);
}
}
}

COM Class Factory Error

I tried in console application it is showing Retrieving the COM class factory for component with CLSID {00024500-0000-0000-C000-000000000046} failed due to the following error: 80040154 Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG)).
This is the error. How to solve this:
static void Main(string[] args)
{
StringBuilder query = new StringBuilder();
query.Append("SELECT deptId ");
query.Append(",[deptabbr], [deptname ], [deptnameLocal] ");
query.Append(",[deptabbrLocal ]");
// , [UnitPrice], [UnitsInStock] ");
//query.Append(",[UnitsOnOrder], [ReorderLevel], [Discontinued] ");
query.Append("FROM [dbo].[mDepartment] ");
//query.Append("JOIN Categories ON Categories.CategoryID = Products.CategoryID ");
//query.Append("ORDER BY Categories.CategoryName ");
SQL.DataTable dtProducts = new SQL.DataTable();
using (SqlConnection cn = new SqlConnection("server=ADMIN-PC;uid=sa;pwd=microsoftsql;database=HPMS_IntranetApp;Integrated Security=True"))
{
using (SqlDataAdapter da = new SqlDataAdapter(query.ToString(), cn))
{
da.Fill(dtProducts);
}
}
Excel.Application oXL;
Excel._Workbook oWB;
Excel._Worksheet oSheet;
oXL = new Excel.Application();
oXL.Visible = true;
oWB = (Excel._Workbook)(oXL.Workbooks.Add(Missing.Value));
oSheet = (Excel._Worksheet)oWB.ActiveSheet;
try
{
SQL.DataTable dtCategories = dtProducts.DefaultView.ToTable(true, "deptId");
foreach (SQL.DataRow category in dtCategories.Rows)
{
oSheet = (Excel._Worksheet)oXL.Worksheets.Add();
oSheet.Name = category[0].ToString().Replace(" ", "").Replace(" ", "").Replace("/", "").Replace("\\", "").Replace("*", "");
string[] colNames = new string[dtProducts.Columns.Count];
int col = 0;
foreach (SQL.DataColumn dc in dtProducts.Columns)
colNames[col++] = dc.ColumnName;
char lastColumn = (char)(65 + dtProducts.Columns.Count - 1);
oSheet.get_Range("A1", lastColumn + "1").Value2 = colNames;
oSheet.get_Range("A1", lastColumn + "1").Font.Bold = true;
oSheet.get_Range("A1", lastColumn + "1").VerticalAlignment = Excel.XlVAlign.xlVAlignCenter;
SQL.DataRow[] dr = dtProducts.Select(string.Format("deptId='{0}'", category[0].ToString()));
string[,] rowData = new string[dr.Count<SQL.DataRow>(), dtProducts.Columns.Count];
int rowCnt = 0;
int redRows = 2;
foreach (SQL.DataRow row in dr)
{
for (col = 0; col < dtProducts.Columns.Count; col++)
{
rowData[rowCnt, col] = row[col].ToString();
}
if (int.Parse(row["deptname"].ToString()) < int.Parse(row["deptnameLocal"].ToString()))
{
Range range = oSheet.get_Range("A" + redRows.ToString(), "J" + redRows.ToString());
range.Cells.Interior.Color = System.Drawing.Color.Red;
}
redRows++;
rowCnt++;
}
oSheet.get_Range("A2", lastColumn + rowCnt.ToString()).Value2 = rowData;
}
oXL.Visible = true;
oXL.UserControl = true;
oWB.SaveAs("Products.xlsx",
AccessMode: Excel.XlSaveAsAccessMode.xlShared);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
Marshal.ReleaseComObject(oWB);
}
}

how to change header column colour in the generated excel

I am exporting data from sql server database to excel in wpf, and I have achieved the function successully. Now I want to change the head column colour in the generated excel. Any ideas? Thanks in advance.
private void button1_Click(object sender, RoutedEventArgs e)
{
string sql = null;
string data = null;
// string path = null;
//string myfilename = "Report";
int i = 0;
int j = 0;
Microsoft.Office.Interop.Excel.Application xlApp;
Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
//xlApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
xlApp = new Microsoft.Office.Interop.Excel.Application();
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
xlWorkSheet.Name = "Customer List";
//connectionString = "data source=servername;initial catalog=databasename;user id=username;password=password;";
//SqlConnection cnn = new SqlConnection(GetConnectionString());
SqlConnection cnn = new SqlConnection();
cnn.ConnectionString = #"Data Source=.\sqlexpress;Initial Catalog=ClientLists;Integrated Security=SSPI;";
cnn.Open();
sql = "select FirstName, LastName, City, PostCode, TelephoneNo from Customers";
SqlDataAdapter dscmd = new SqlDataAdapter(sql, cnn);
DataSet ds = new DataSet();
dscmd.Fill(ds);
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();
xlWorkSheet.Cells[i + 2, j + 1] = data;
}
}
Microsoft.Office.Interop.Excel.Range headerRange1 = xlWorkSheet.get_Range("A1", "A1");
headerRange1.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
headerRange1.Value = "First Name";
headerRange1.Font.Bold = true;
headerRange1.ColumnWidth = 14;
// headerRange1.Interior.Color = 1;
// headerRange1.Borders.Color = System.Drawing.Color.Red;
Microsoft.Office.Interop.Excel.Range headerRange2 = xlWorkSheet.get_Range("B1", "B1");
headerRange2.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
headerRange2.Value = "Last Name";
headerRange2.Font.Bold = true;
headerRange2.ColumnWidth = 14;
Microsoft.Office.Interop.Excel.Range headerRange3 = xlWorkSheet.get_Range("C1", "C1");
headerRange3.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
headerRange3.Value = "City";
headerRange3.Font.Bold = true;
headerRange3.ColumnWidth = 14;
Microsoft.Office.Interop.Excel.Range headerRange4 = xlWorkSheet.get_Range("D1", "D1");
headerRange4.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
headerRange4.Value = "Post Code";
headerRange4.Font.Bold = true;
headerRange4.ColumnWidth = 14;
Microsoft.Office.Interop.Excel.Range headerRange5 = xlWorkSheet.get_Range("E1", "E1");
headerRange5.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
headerRange5.Value = "Telephone NO";
headerRange5.Font.Bold = true;
headerRange5.ColumnWidth = 14;
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
}
private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
MessageBox.Show("Exception Occured while releasing object " + ex.ToString());
}
finally
{
GC.Collect();
}
}
}
}
There is a post that can be found here that says that this is not possible.
However, the c# excel how to change a color of a particular row post on StackOverflow that provides code for changing a row colour... you may be able to adapt it for you purposes.

Resources