Excel sheet read only and C# - c#

I'm trying to edit an Excel Sheet through C# code but the Excel sheet is giving me an error saying read only
CS0200 Property or indexer 'Range.Text' cannot be assigned to -- it is read only
This is the code that is trying to access the sheet.
Code:
//Load workbook
Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(#"S:\Utils\documents\ServerManager\serverlist.xlsx");
Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1];
Excel.Range xlRange = xlWorksheet.UsedRange;
xlWorksheet.Range["D2"].Text = "Kelly Cooper";
xlWorksheet.Range["D2"].Style.Font.FontName = "Arial Narrow";
xlWorksheet.Range["D2"].Style.Font.Color = Color.DarkBlue;
In the properties the Excel sheet is not read only and when I open it to edit it does not prompt me with the "This document is read only, want to enable editing." How can I go around this, Visual Studio won't let me compile because of it.
This is Excel in Office365.

You want to use .Value instead of .Text.
xlWorksheet.Range["D2"].Value = "Kelly Cooper";
xlWorksheet.Range["D2"].Style.Font.FontName = "Arial Narrow";
xlWorksheet.Range["D2"].Style.Font.Color = Color.DarkBlue;
If you check the documentation you can see that Text is read-only.
Also, if you check the documentation you can see that Value is not read-only.
EDIT
You also might have to change your Open parameters to:
Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(Filename: "path/to/file", ReadOnly: false);

Related

not able to copy excel column values to specified range in another excel file

I have written a small code to copy few columns from source excel file to another excel file (destination excel file) using c#. Below is sample image of source excel file.
The expected result in destination excel file should be as shown in below image.
Below is my code
string fileTarget = #"C:\Users\sia\Desktop\Excel Automation\destination.xlsx";
string fileTemplate = #"C:\Users\sia\Desktop\Excel Automation\source.xlsx";
Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook wbTemp, wbTarget;
Microsoft.Office.Interop.Excel.Worksheet sh;
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook wbSource = excel.Workbooks.Open(fileTemplate, ReadOnly: false);
Microsoft.Office.Interop.Excel.Worksheet WorksheetSource = wbSource.Sheets[1];
//Copy all range in this worksheet
WorksheetSource.UsedRange.Copy(Type.Missing);
//Open destination workbook
Microsoft.Office.Interop.Excel.Workbook wbDestination = excel.Workbooks.Open(fileTarget, ReadOnly: false);
Microsoft.Office.Interop.Excel.Worksheet WorksheetDestination = wbDestination.Sheets[1];
WorksheetDestination.UsedRange.PasteSpecial(Microsoft.Office.Interop.Excel.XlPasteType.xlPasteAll, Microsoft.Office.Interop.Excel.XlPasteSpecialOperation.xlPasteSpecialOperationNone, Type.Missing, Type.Missing);
wbDestination.SaveAs(#"C:\Users\sia\Desktop\Excel Automation\destination.xlsx");
wbSource.Close();
excel.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);
But the i'm not getting the expected format, below is the result I'm getting.
where and what modification i need to do in my existing code to get the expected result.
Thanks
You need to specify proper column and range, otherwise by default paste will go in the first column
workSheet.Range
For reference: Copy/paste cells in Excel with C#

Reading to an Excel file

I am trying to read an excel sheet using C# and store each row into an array. I am able to open the file but the code I am using currently reads to an "2D-Object" array but I would like to read the info into 1D-string arrays.
static void Main(string[] args)
{
// Reference to Excel Application.
Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(Path.GetFullPath("excelpractice1.xlsx"));
// Get the first worksheet.
Excel.Worksheet xlWorksheet = (Excel.Worksheet)xlWorkbook.Sheets.get_Item(1);
// Get the range of cells which has data.
Excel.Range xlRange = xlWorksheet.UsedRange;
// Get an object array of all of the cells in the worksheet with their values.
object[,] valueArray = (object[,])xlRange.get_Value(Excel.XlRangeValueDataType.xlRangeValueDefault);
// Close the Workbook.
xlWorkbook.Close(false);
// Relase COM Object by decrementing the reference count.
Marshal.ReleaseComObject(xlWorkbook);
// Close Excel application.
xlApp.Quit();
// Release COM object.
Marshal.FinalReleaseComObject(xlApp);
Console.ReadLine();
}
}
}
`
Sorry, I was trying to comment only. =X
But did it worked for you anyway? LinqToExcel is a great library for manipulate spreadsheets!
Please, let me know if has any doubt yet.
=)

Searching date string in file excel

I'm working with an excel file and I'm trying to find the position(address) of the cells with date value like "16/02/2015" as content. In order to do this with windows Forms application I use a datetimepicker. My code is as following:
// Firstly I want a string like 16/02/2015 inserted in the datetimepicker
string date = DateTimePicker1.Value.ToString().Substring(0,10);
List<string> Testsdone = new List<string>();
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Open(file_opened, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(4);
Excel.Range currentFind = null;
Excel.Range firstFind = null;
Excel.Range tests = xlWorkSheet.get_Range("K13", "K2295");
currentFind = tests.Find(date);
.....
I have exactly the same content "16/02/2015" written in my excel file, but the currectFind always shows null! I have no idea why the two "16/02/2015" are different. Anybody got an idea? thanks!
Well after some investigation I found that the problem is caused by the Find function
currentFind = tests.Find(date);
which for unknown reason failed to find the date. From another post
how to Search in excel file I got this method, that I changed this into:
currentFind = xlworkSheet.Cells.Find(date, Type.Missing, Microsoft.Office.Interop.Excel.XlFindLookIn.xlValues, Microsoft.Office.Interop.Excel.XlLookAt.xlWhole, Microsoft.Office.Interop.Excel.XlSearchOrder.xlByRows,Microsoft.Office.Interop.Excel.XlSearchDirection.xlNext, false,Type.Missing, Type.Missing);
And it works. But I still have no idea why the Excel.Range.Find fails and Excel.workersheet.Cells.Find works

Excel worksheet get item

I have a problem with Excel worksheet. I am trying to create an Excel file with c#.
This code works and runs correctly on my computer but in other computers get an error at last line:
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheetInvoice;
Excel.Worksheet xlWorkSheetInvoiceLine;
object misValue = System.Reflection.Missing.Value;
xlApp = new Microsoft.Office.Interop.Excel.Application();
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheetInvoice = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
xlWorkSheetInvoiceLine = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(2);
System.Runtime.InteropServices.COMException (0x8002000B): Invalid index. (Exception from HRESULT: 0x8002000B (DISP_E_BADINDEX))
at Microsoft.Office.Interop.Excel.Sheets.get_Item(Object Index)
I executed a sample application with similar code on a machine with Excel 2013 and it fails at the same line of code you mentioned. By default Excel 2013 application opens up with a single worksheet ("Sheet1") so you would have to modify the code accordingly
DISP_E_BADINDEX seems to suggest the number of worksheets is less on the other computers. Build in a check to see if the number of worksheets is less than 2 before using get_Item().
i have created new sheet and assigned xlWorkSheetInvoice and xlWorkSheetInvoiceLine to solve it.
var xlSheets = xlWorkBook.Sheets as Excel.Sheets;
var xlNewSheet = (Excel.Worksheet)xlSheets.Add(xlSheets[1], Type.Missing, Type.Missing, Type.Missing);
var xlNewSheet2= (Excel.Worksheet)xlSheets.Add(xlSheets[2], Type.Missing, Type.Missing, Type.Missing);
xlWorkSheetInvoice = xlNewSheet;
xlWorkSheetInvoiceLine = xlNewSheet2;
xlWorkSheetInvoice = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
xlWorkSheetInvoiceLine = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(2);

C# Automating to Excel

...
Excel.Application oXL;
Excel._Workbook oWB;
Excel._Worksheet oSheet;
oXL = new Excel.Application();
oWB = (Excel._Workbook)oXL.ActiveWorkbook;
oSheet = (Excel._Worksheet)oWB.Sheets[1];
oSheet.Cells[5,10] = "Value";
...
yields this at crash:
Unhandled Exception: System.NullReferenceException: Object reference not set to
an instance of an object.
at ConsoleApplication1.Program.Main(String[] args) in C:\Wherever\Visual Studio 2008\Projects\ConsoleApplication20\ConsoleApplication20\Program.
cs:line 60
In this case, line 60 is
oSheet = (Excel._Worksheet)oWB.Sheets[1];
and the same thing happens if the line is written
oSheet = (Excel._Worksheet)oWB.ActiveSheet;.
Excel is already open onscreen at the time, with a fresh worksheet in place.
The error is telling you that oWB is null. It is null because unlike opening Excel from a GUI, automation does not create a new 3-sheet book. You need to specifically load a book first, or add one.
See example here http://support.microsoft.com/kb/302084 where it explicitly adds a new workbook to play with
//Get a new workbook.
oWB = (Excel._Workbook)(oXL.Workbooks.Add( Missing.Value ));

Categories