how to change header column colour in the generated excel - 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.

Related

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...

Import EXCEL with SSIS without knowing sheename

I'm trying to use SSIS to import multiple files from a folder, and i dont know the SheetName.
So, I'm creating a script task according to below link, to get SheetName, but i got error in the script task 'array size cannot be specified in a variable declaration'
http://www.anupamanatarajan.com/2011/01/dynamic-sheet-name-in-ssis-excel.html
public void Main()
{
// TODO: Add your code here
string excelFile = null;
string connectionString = null;
OleDbConnection excelConnection = null;
DataTable tablesInFile = null;
int tableCount = 0;
DataRow tableInFile = null;
string currentTable = null;
int tableIndex = 0;
string[] excelTables = null;
excelFile = Dts.Variables["User::BBGFilePath"].Value.ToString();
connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + excelFile + ";Extended Properties=Excel 8.0";
excelConnection = new OleDbConnection(connectionString);
excelConnection.Open();
tablesInFile = excelConnection.GetSchema("Tables");
tableCount = tablesInFile.Rows.Count;
excelTables = new string[tableCount];
foreach (DataRow tableInFile_loopVariable in tablesInFile.Rows)
{
tableInFile = tableInFile_loopVariable;
currentTable = tableInFile["TABLE_NAME"].ToString();
excelTables[tableIndex] = currentTable;
tableIndex += 1;
}
}
//Provide value to the shetename variable
Dts.Variables["User::SheetName"].Value = excelTables[0];
//Display file name
string strMessage = Dts.Variables["User::BBGFilePath"].Value.ToString();
MessageBox.Show(strMessage);
Dts.TaskResult = (int)ScriptResults.Success;
}
So i tried to add the [User:SheetName] variable to the Script task, but it doesn't work.
can anyone please check what is missing?
As I had mentioned earlier, the error does clearly suggested you have some non-declaration statements at the class level which is not valid.
Your code from the script task have some issues with the closing brace --
public void Main()
{
// TODO: Add your code here
string excelFile = null;
string connectionString = null;
OleDbConnection excelConnection = null;
DataTable tablesInFile = null;
int tableCount = 0;
DataRow tableInFile = null;
string currentTable = null;
int tableIndex = 0;
string[] excelTables = null;
excelFile = Dts.Variables["User::BBGFilePath"].Value.ToString();
//Provider = Microsoft.Jet.OLEDB.4.0; Data Source = C:\CESLtd\ELKAY\Reports\Work2\Book1.xls; Extended Properties = "EXCEL 8.0;HDR=YES";
connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + excelFile + ";Extended Properties=Excel 8.0;HDR=YES";
excelConnection = new OleDbConnection(connectionString);
excelConnection.Open();
tablesInFile = excelConnection.GetSchema("Tables");
tableCount = tablesInFile.Rows.Count;
excelTables = new string[tableCount];
foreach (DataRow tableInFile_loopVariable in tablesInFile.Rows)
{
tableInFile = tableInFile_loopVariable;
currentTable = tableInFile["TABLE_NAME"].ToString();
excelTables[tableIndex] = currentTable;
tableIndex += 1;
}
//} **commented this line now you are good to go**
//Provide value to the shetename variable
Dts.Variables["User::SheetName"].Value = excelTables[0];
//Display file name
string strMessage = Dts.Variables["User::BBGFilePath"].Value.ToString();
MessageBox.Show(strMessage);
Dts.TaskResult = (int)ScriptResults.Success;
}

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);
}
}

Export xml data to Excel using OpenXML

The file is downloading an xlsx file but when i tried to open the file it is saying file is corrupted. Here is the code i'm trying to use please let me know if any changes has to be done for the following.
private void button1_Click(object sender, EventArgs e)
{
ArrayList DataNode = new ArrayList();
XmlDocument xmlobj = new XmlDocument();
ArrayList FinalXML = new ArrayList();
XslCompiledTransform xXslt = new XslCompiledTransform();
xmlobj.Load(#"D:\ExcelImport\Input.xml");
xXslt.Load(#"D:\ExcelImport\demoxsl.xslt");
XmlNodeList DN ;
DN = xmlobj.DocumentElement.GetElementsByTagName("Data");
for (int i = 0; i < DN.Count; i++)
{
DataNode.Add("<ShaleDataExport><Data Flag = '" + i + "' >" + DN.Item(i).InnerXml + "</Data></ShaleDataExport>");
}
string ShaleDataExportXML;
int k = 0 ;
while (k < DN.Count)
{
ShaleDataExportXML = DataNode[k].ToString();
XmlDocument xml = new XmlDocument();
xml.LoadXml(ShaleDataExportXML);
StringWriter sw = new StringWriter();
xXslt.Transform(xml, null, sw);
FinalXML.Add(sw);
sw.Close();
k++;
}
using (SpreadsheetDocument doc = SpreadsheetDocument.Create(#"D:\ExcelImport\OutPut\OutPut.xlsx", DocumentFormat.OpenXml.SpreadsheetDocumentType.Workbook))
{
WorkbookPart workbook = doc.AddWorkbookPart();
string XML;
string WorbookXML;
WorbookXML = #"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?><workbook xmlns=""schemas.openxmlformats.org/.../main"" xmlns:r=""schemas.openxmlformats.org/.../relationships""><sheets>";
for (int j = 0; j < DN.Count; j++)
{
WorksheetPart[] sheet = new WorksheetPart[DN.Count];
sheet[j] = workbook.AddNewPart<WorksheetPart>();
string sheetId = workbook.GetIdOfPart(sheet[j]);
XML = #"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?><worksheet xmlns=""schemas.openxmlformats.org/.../main"" >";
XML += FinalXML[j].ToString() + "</worksheet>";
string SheetXML = XML.ToString();
XmlDocument SXML = new XmlDocument();
SXML.LoadXml(SheetXML);
byte[] byteArray = Encoding.ASCII.GetBytes(SXML.OuterXml);
MemoryStream stream = new MemoryStream(byteArray);
StreamReader reader = new StreamReader(stream);
string text = reader.ReadToEnd();
WorbookXML += "<sheet name="+ AddPartXml(sheet[j], text) + " sheetId=" + j.ToString() + " r:id=" + sheetId.ToString() + " />";
}
WorbookXML += "</sheets></workbook>";
AddPartXml(workbook, WorbookXML);
doc.Close();
}
}
public string AddPartXml(OpenXmlPart part, string xml)
{
Uri uri = part.Uri;
String[] sheetNames = uri.OriginalString.Split('/');
string sheetName = sheetNames[sheetNames.Length - 1].Split('.')[0];
using (Stream stream = part.GetStream())
{
byte[] buffer = (new UTF8Encoding()).GetBytes(xml);
stream.Write(buffer, 0, buffer.Length);
}
return sheetName;
}
Thanks in advance
Vineet Mangal
private void button1_Click(object sender, EventArgs e)
{
XmlDocument xmlobj = new XmlDocument();
xmlobj.Load(#"C:\Excel Import\\Input.xml");
XslCompiledTransform xXslt = new XslCompiledTransform();
xXslt.Load(#"C:\ExportToexcel\Data.xslt");
StringWriter sw = new StringWriter();
xXslt.Transform(xmlobj, null, sw);
richTextBox2.Text = sw.ToString();
sw.Close();
XmlDocument Xdoc = new XmlDocument();
Xdoc.LoadXml(sw.ToString());
Xdoc.Save(#"c:\temp\output.xml");
StreamReader sr = File.OpenText(#"c:\temp\output.xml");
string strSheetData = sr.ReadToEnd();
ArrayList DataNode = new ArrayList();
ArrayList FinalXML = new ArrayList();
XmlNodeList DN;
DN = xmlobj.DocumentElement.GetElementsByTagName("Data");
for (int i = 0; i < DN.Count; i++)
{
DataNode.Add("<ShaleDataExport><Data Flag = '" + i + "' >" + DN.Item(i).InnerXml + "</Data></ShaleDataExport>");
}
string ShaleDataExportXML;
int k = 0;
while (k < DN.Count)
{
ShaleDataExportXML = DataNode[k].ToString();
XmlDocument xml = new XmlDocument();
xml.LoadXml(ShaleDataExportXML);
StringWriter sw1 = new StringWriter();
xXslt.Transform(xml, null, sw1);
FinalXML.Add(sw1);
sw.Close();
k++;
}
using (SpreadsheetDocument doc = SpreadsheetDocument.Create(#"c:\\temp\\output.xlsx", DocumentFormat.OpenXml.SpreadsheetDocumentType.Workbook))
{
WorkbookPart workbook1 = doc.AddWorkbookPart();
string XML;
string WorbookXML;
WorbookXML = #"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?><workbook xmlns=""http://schemas.openxmlformats.org/spreadsheetml/2006/main"" xmlns:r=""http://schemas.openxmlformats.org/officeDocument/2006/relationships""><sheets>";
for (int j = 0; j < DN.Count; j++)
{
WorksheetPart[] sheet = new WorksheetPart[DN.Count];
sheet[j] = workbook1.AddNewPart<WorksheetPart>();
string sheetId = workbook1.GetIdOfPart(sheet[j]);
XML = #"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?><worksheet xmlns=""http://schemas.openxmlformats.org/spreadsheetml/2006/main"" >";
XML += FinalXML[j].ToString() + "</worksheet>";
string SheetXML = XML.ToString();
XmlDocument SXML = new XmlDocument();
SXML.LoadXml(SheetXML);
byte[] byteArray = Encoding.ASCII.GetBytes(SXML.OuterXml);
MemoryStream stream = new MemoryStream(byteArray);
StreamReader reader = new StreamReader(stream);
string text = reader.ReadToEnd();
**WorbookXML += "<sheet name=" + "\"sheet" + (j + 1).ToString() + "\" " + " sheetId=\"" + (j + 1).ToString() + "\" r:id=\"" + sheetId.ToString() + "\" />";
AddPartXml(sheet[j], text);**
}
WorbookXML += "</sheets></workbook>";
AddPartXml(workbook1, WorbookXML);
doc.Close();
}
}
public void AddPartXml(OpenXmlPart part, string xml)
{
**using (Stream stream = part.GetStream())
{
byte[] buffer = (new UTF8Encoding()).GetBytes(xml);
stream.Write(buffer, 0, buffer.Length);
}**
}

Can any find my mistake while dumping the data into excel?

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.

Resources