How to append a data to existing excel file using c# - c#

I want to append a data to a existing excel file using c#.I Tried it using below codes,but it is giving wrong column value after opening of the excel file(if my excel file contains 4 columns,but here it is returning column count as 1 only).
xlApp = new Excel.Application();
xlApp.Visible = true;
xlWorkBook = xlApp.Workbooks.Open(fileName, 0, false, 5, "", "", false,
Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true, false, 0, true, 1, 0); //#"H:\TestFile.xlsx"
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Sheets.get_Item(sheetNum);
rng = xlWorkSheet.UsedRange;
int colCount = rng.Columns.Count;
int rowCount = rng.Rows.Count;
rng = (Excel.Range)xlWorkSheet.Cells[rowCount, colCount];
Excel.Range newColumn = rng.EntireColumn;
xlWorkSheet.Cells[1, colCount + 3] = "Udupi";
xlWorkBook.Save();
xlWorkBook.Close(misValue, misValue, misValue);
xlApp.Quit();
How can i append a data to excel file?Is there any other methods are available to achieve this one!

Have you tried Epplus library for creating and editing Excel spreadsheets and workbooks in C#? I have worked on it before some weeks ago. It is super. I recommend to use it.

Related

Save/Close Excel Workbook and quit excel with no popups c#

I have the below code which works to delete the first row of a specified excel workbook. After this is done I would like to save (Overwrite changes) and exit the excel applications.
I gathered this may be achieved by Workbook.Close(True) but the popups still occur and the Object workbook is not referenced.
Any help would be much appreciated.
public void DeleteRows(string workbookPath)
{
// New Excel Application
Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();
//Open WorkBook
Microsoft.Office.Interop.Excel.Workbook excelWorkbook = excelApp.Workbooks.Open(workbookPath,
0, false, 5, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "",
true, false, 0, true, false, false);
Microsoft.Office.Interop.Excel.Sheets excelSheets = excelWorkbook.Worksheets;
string currentSheet = "Sheet1";
Microsoft.Office.Interop.Excel.Worksheet excelWorksheet = (Microsoft.Office.Interop.Excel.Worksheet)excelSheets.get_Item(currentSheet);
Microsoft.Office.Interop.Excel.Range excelCell = (Microsoft.Office.Interop.Excel.Range)excelWorksheet.get_Range("A1", "A1");
Microsoft.Office.Interop.Excel.Range row = excelCell.EntireRow;
row.Delete(Microsoft.Office.Interop.Excel.XlDirection.xlUp);
}
Honestly, all I think that's missing from your code is a save and close. Once you save, the warning should not be issued.
using Excelx = Microsoft.Office.Interop.Excel;
public void DeleteRows(string workbookPath)
{
// New Excel Application
Excelx.Application excelApp = new Excelx.Application();
//Open WorkBook
Excelx.Workbook excelWorkbook = excelApp.Workbooks.Open(workbookPath,
0, false, 5, "", "", false, Excelx.XlPlatform.xlWindows, "",
true, false, 0, true, false, false);
Excelx.Sheets excelSheets = excelWorkbook.Worksheets;
string currentSheet = "Sheet1";
Excelx.Worksheet excelWorksheet = (Excelx.Worksheet)excelSheets.get_Item(currentSheet);
Excelx.Range excelCell = (Excelx.Range)excelWorksheet.get_Range("A1", "A1");
Excelx.Range row = excelCell.EntireRow;
row.Delete(Excelx.XlDirection.xlUp);
// This should be all you need:
excelWorkbook.Save();
excelWorkbook.Close();
}
I'd be puzzled if this doesn't work, but if it doesn't, it might help when you are debugging to make Excel visible and step through the code:
excelApp.Visible = true;
As a final last attempt, before you save, you can disable warnings which will tell Excel to dispense with any of the dialogs to try to save you from yourself:
excelApp.DisplayAlerts = false;
excelWorkbook.Save();
excelWorkbook.Close();
excelApp.DisplayAlerts = true;
And again, I think you shouldn't even get to step 2 for this to work, but let me know if it doesn't. We would have quite a puzzle.

Delete first row in Excel Workbook - Object Reference required error c#

I have been using the "Code Project" and "Stackoverflow" to create a script which will delete the first row of a specified excel workbook.
I am having an issue with line 13 "Range.EntireRow;" with the error "An object reference is required for the non-static field, method, or property Range.Entire.Row
Please see the script I have created below;
public void DeleteRows(string workbookPath)
{
// New Excel Application
Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();
//Open WorkBook
Microsoft.Office.Interop.Excel.Workbook excelWorkbook = excelApp.Workbooks.Open(workbookPath,
0, false, 5, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "",
true, false, 0, true, false, false);
Microsoft.Office.Interop.Excel.Sheets excelSheets = excelWorkbook.Worksheets;
string currentSheet = "Sheet1";
Microsoft.Office.Interop.Excel.Worksheet excelWorksheet = (Microsoft.Office.Interop.Excel.Worksheet)excelSheets.get_Item(currentSheet);
Microsoft.Office.Interop.Excel.Range excelCell = (Microsoft.Office.Interop.Excel.Range)excelWorksheet.get_Range("A1", "A1");
Microsoft.Office.Interop.Excel.Range row = Range.EntireRow; //ERROR Line
row.Delete(Microsoft.Office.Interop.Excel.XlDirection.xlUp);
Any advice on how to fix this error would be greatly appreciated.
You could refer to the Cells of the Range to get the entire row:
Microsoft.Office.Interop.Excel.Range row = excelCell.Cells.EntireRow
or even omitting the Cells should work as well:
Microsoft.Office.Interop.Excel.Range row = excelCell.EntireRow
MSDN Range.EntireRow Property
You should use: Microsoft.Office.Interop.Excel.Range row = excelCell.EntireRow;

How to insert data to Excel Sheet

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];

Read Excel First Column using C# into Array

I'm trying to read in the values of the first column into an array. What's the best way to do that? Below is the code I have so far. Basically I'm trying to get the range of data for that column so I can pull the cell values into a system array.
Microsoft.Office.Interop.Excel.Application xlsApp = new Microsoft.Office.Interop.Excel.Application();
if (xlsApp == null)
{
Console.WriteLine("EXCEL could not be started. Check that your office installation and project references are correct.");
return null;
}
//xlsApp.Visible = true;
Workbook wb = xlsApp.Workbooks.Open(filename, 0, true, 5, "", "", true, XlPlatform.xlWindows, "\t", false, false, 0, true);
Sheets sheets = wb.Worksheets;
Worksheet ws = (Worksheet)sheets.get_Item(1);
//***Breaks Here***
ListColumn column = ws.ListObjects[1].ListColumns[1];
Range range = column.DataBodyRange;
System.Array myvalues = (System.Array)range.Cells.Value;
Here is what I ended up using to get it to work. Once you know that Columns actually returns a range, storing it that way seems to compile and run fine. Here is the working method in my ExcelReader class. I plan to use this for test driven data on WebDriver.
public static string[] FirstColumn(string filename)
{
Microsoft.Office.Interop.Excel.Application xlsApp = new Microsoft.Office.Interop.Excel.Application();
if (xlsApp == null)
{
Console.WriteLine("EXCEL could not be started. Check that your office installation and project references are correct.");
return null;
}
//Displays Excel so you can see what is happening
//xlsApp.Visible = true;
Workbook wb = xlsApp.Workbooks.Open(filename,
0, true, 5, "", "", true, XlPlatform.xlWindows, "\t", false, false, 0, true);
Sheets sheets = wb.Worksheets;
Worksheet ws = (Worksheet)sheets.get_Item(1);
Range firstColumn = ws.UsedRange.Columns[1];
System.Array myvalues = (System.Array)firstColumn.Cells.Value;
string[] strArray = myvalues.OfType<object>().Select(o => o.ToString()).ToArray();
return strArray;
}
First, I'd work out how many rows are actually being used:
Excel.Range allCellsInColumn = xlWorksheet.Range["A:A"];
Excel.Range usedCells = allCellsInColumn.Find("*", Missing.Value, Missing.Value, Missing.Value,
Excel.XlSearchOrder.xlByRows, Excel.XlSearchDirection.xlPrevious, false, Missing.Value, Missing.Value);
Once you have that you can retrieve the values:
System.Array values = usedCells.Values;
Once you have the values in the array you can skip over the elements with nothing in them. I don't think there is a way of retrieving just the cells with something in them without looping through them one at a time, which is very time consuming in Interop.
Is your data in a list? Your code seems to be looking for an Excel List which may not be present. If not you can just get the entire first column (A:A) into a Range and get it's Value:
Range firstCol = ws.Range("A:A");
System.Array values = range.Value as System.Array;

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