How to insert data to Excel Sheet - c#

I have a file Excel contains 4 Sheets, how can I write data to sheet 2 without using OLEDB, and I want to write data cell by cell...
Could any one help me ?
I have a code like this :
Excel._Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
private void button1_Click(object sender, EventArgs e)
{
Excel._Application xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Open("E:\\Project Skripsi\\normalisasi.xlsx", 0, true, 5, "", "", true, Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
xlWorkSheet.Cells[1, 1].Value2 = Convert.ToInt32(xlWorkSheet.Cells[1, 1].Value2) + 1;
xlWorkBook.Close(false, misValue, misValue);
xlApp.Quit();
}

For using worksheet 2 you will have to use this..
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(2);
This means that xWorkSheet object is pointing to the sheet2 and values you added to the cells would be added to sheet2.
And u can add values to cells using this,
xlWorkSheet.Cells[1, 1] = "YourValue(Could be of any data type)";

With Office-Interop you can access the different sheets by using the index on the Worksheet-property in the Workbook object:
//select the first sheet
Excel.Worksheet sheet1 = (Worksheet) xlWorkBook.Worksheets[1];
//select the second sheet
Excel.Worksheet sheet2 = (Worksheet) xlWorkBook.Worksheets[2];

Related

How to read specific column in excel using c# and get the number of occurrences of different words in that column

I want to find the number of occurrences of different words in column H using C# and ignore the null values. Later, I have to display the output in List box. I am using the Microsoft.Office.Interlop.Excel reference to open workbook and access the first worksheet.
I tried the following code :
private void button3_Click(object sender, EventArgs e)
{
Excel.Application xlApp;
Excel.Workbook xlWorkbook;
Excel.Worksheet xlWorksheet;
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.Application();
xlWorkbook = xlApp.Workbooks.Open("ABC.xlsx", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
xlWorksheet = (Excel.Worksheet)xlWorkbook.Worksheets.get_Item(1);
Excel.Range bColumn = xlWorksheet.UsedRange.Columns[4, Type.Missing].Columns.Count;
List<string> dataItems = new List<string>();
foreach (object o in bColumn)
{
Excel.Range row = o as Excel.Range;
string s = row.get_Value(null);
dataItems.Add(s);
}
listBox1.DataSource = dataItems;
xlWorkbook.Close(true, misValue, misValue);
xlApp.Quit();
releaseObject(xlWorksheet);
releaseObject(xlWorkbook);
releaseObject(xlApp);
}
Please help me out with the code and suggest the fastest possible approach as the worksheet contains more than a thousand rows.
Thanks in advance for the help!
For example, if you want to find all values in column C then:
object[] columnValue = xlWorksheet.Range["C"].Values2;
the columnValue will be the values in the excel.
So it would be a lot faster if you do it in memory, you can first convert it to a string list using columnValue.Select(a=>a == null ? null : a.ToString()).ToList() then you will be able to do all sort of logic such as using Distinct to get the distinct values, count to get the occurence and so on.

How do I set the order of Worksheets as I add them to Excel Programmatically?

I have an Excel work book that I am adding work sheets using a loop. In the sample code below I am using a fixed array but the real code uses a database to get the names from and there can be one or many (less than 10 though).
The issue that I am having (with my code) is the worksheets get added in the reverse order of the array. So the excel sheet will open with the tabs ordered like this 1103 1102 1101 Sheet1. I know I can reorder the results from the database but that feels like a hack and I am sure there is a way to accomplish this in code. What needs to be done to set the order of tabs correctly inside my loop?
private static void SetWorksheet()
{
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.Application();
xlApp.Visible = true;
xlWorkBook = xlApp.Workbooks.Add(1);
string[] storeArray = { "1101", "1102", "1103" };
foreach (string s in storeArray)
{
xlWorkBook.Worksheets.Add();
xlWorkBook.Worksheets.Move(After: xlWorkBook.Sheets[xlWorkBook.Sheets.Count]);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Sheets[1];
xlWorkSheet.Name = s;
releaseObject(xlWorkSheet);
}
releaseObject(xlWorkBook);
releaseObject(xlApp);
}
You can add new worksheet after the last sheet by put parameter 'After' in Add function.
xlWorkBook.Worksheets.Add(After: xlWorkBook.Sheets[xlWorkBook.Sheets.Count]);
Then you do not need to move it by using Move function.
And in the line
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Sheets[1];
It always get first sheet to change the name.
You need to change '1' to xlWorkBook.Sheets.Count
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Sheets[xlWorkBook.Sheets.Count];
Finally your code should be as below
private static void SetWorksheet()
{
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.Application();
xlApp.Visible = true;
xlWorkBook = xlApp.Workbooks.Add(1);
string[] storeArray = { "1101", "1102", "1103" };
foreach (string s in storeArray)
{
xlWorkBook.Worksheets.Add(After: xlWorkBook.Sheets[xlWorkBook.Sheets.Count]);
//xlWorkBook.ActiveSheet(After: xlWorkBook.Sheets[xlWorkBook.Sheets.Count]);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Sheets[xlWorkBook.Sheets.Count];
xlWorkSheet.Name = s;
releaseObject(xlWorkSheet);
}
releaseObject(xlWorkBook);
releaseObject(xlApp);
}
you can add a new work sheet after 3 sheet in default in excel but you can add more then one sheet by using below code:
Microsoft.Office.Interop.Excel.Worksheet sheet1 = (Microsoft.Office.Interop.Excel.Worksheet)excelApp.Sheets.get_Item(1);
Microsoft.Office.Interop.Excel.Worksheet sheet4 = (Microsoft.Office.Interop.Excel.Worksheet)excelApp.Sheets.Add(After: wb.Sheets[3]);

How to open an Excel worksheet on "worksheet Name" basis and not by the "number of worksheets" using Windows form application

Excel.Application xlApp ;
Excel.Workbook xlWorkBook ;
Excel.Worksheet xlWorkSheet ;
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.ApplicationClass();
xlWorkBook = xlApp.Workbooks.Open("csharp.net-informations.xls", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
I have the above code...but I wanted to search the worksheet based on its name and not number.
string someName="My worksheet";
int i=0;
do {
i+=1;
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(i);
} while(xlWorksheet.Name!=someName);
Instead of this:
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
Use below code:
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets["sheetname"];

Insert text in specific cell in Excel c#

I need to insert text in 5th row ist column and another text in 5th row 2nd column... How do I do this? Below is the code am using and get out of range exception:
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
Excel.Worksheet xlWorkSheet2;
Excel.Worksheet xlWorkSheet3;
Excel.Range oRange;
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet2 = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
xlWorkSheet2.Name = "The chart sheet";
xlWorkSheet2.Cells[5, 1] = "First Name";
xlWorkSheet2.Cells[5,2] = "Last Name";
Before the cell insertion above you have to add a worksheet
Excel.Application excelApplication = new Excel.Application();
Excel.Workbook excelWorkBook = excelApplication.Workbooks.Add();
Excel.Worksheet wkSheetData = excelWorkBook.ActiveSheet;
excelApplication.Cells[5, 2] = "TextField";
I hope this helps

Open, Modify, SaveAs an Excel Workbook in the background (Winforms, C#)

in my app, I've saved a copy of a blank excel file form as a resources, I need to load this file, modify its both worksheets, save it in a new location with a new name.
user should not see that process.
I'm using C# 2010 with a SQL server, from which I'm gonna load my data and put it in the excel form.
Thank You For Your Time.
Use the Microsoft Interop Assemblies that can be found in .NET or COM (Microsoft.Office.Interop.Excel)
Then load all the required cells into a List and modify the data.
Something like this (code below):
string path = #"C:\temp\test.xls";
ApplicationClass excelApllication = null;
Workbook excelWorkBook = null;
Worksheet excelWorkSheet = null;
excelApllication = new ApplicationClass();
System.Threading.Thread.Sleep(2000);
excelWorkBook = excelApllication.Workbooks.Add();
excelWorkSheet = (Worksheet)excelWorkBook.Worksheets.get_Item(1);
// Attention: 1 indexed cells, [Row, Col]
excelWorkSheet.Cells[1, 1] = "Column A, Row 1";
excelWorkSheet.Cells[2, 5] = "Column E, Row 2";
excelWorkSheet.Cells[3, 3] = "Column C, Row 3";
excelWorkBook.SaveAs(path, XlFileFormat.xlWorkbookNormal);
excelWorkBook.Close();
excelApllication.Quit();
Marshal.FinalReleaseComObject(excelWorkSheet);
Marshal.FinalReleaseComObject(excelWorkBook);
Marshal.FinalReleaseComObject(excelApllication);
excelApllication = null;
excelWorkSheet = null;
//opens the created and saved Excel file
Process.Start(path);
That should happen inside a Thread, because you don't want a user to notice that task.
http://msdn.microsoft.com/en-us/library/aa645740%28v=vs.71%29.aspx
(Threading Tutorial)
I would try to avoid automating Excel if at all possible and use the OpenXML SDK (or a library wrapping the OpenXML SDK) for this task.
Here is an article that could help you get started.
I think you wanted to do this... at least worked for me. :)
private void btnExcel_Click(object sender, EventArgs e)
{
string newDirectoryPath = ValidateDirectory();
string newFilePath = Path.Combine(newDirectoryPath, "new.xls");
//brand new temporary file
string tempPath = System.IO.Path.GetTempFileName();
//to manage de temp file life
FileInfo tempFile = new FileInfo(tempPath);
//copy the structure and data of the template .xls
System.IO.File.WriteAllBytes(tempPath,Properties.Resources.SomeResource);
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Open(tempPath, 0, true, 5, "", "", true, Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
//WorkTheExcelFile();
tempFile.Delete();
xlWorkBook.SaveAs(newFilePath);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
Process.Start(newFilePath + ".xlsx");
}

Categories

Resources