Check if worksheet exist using infragistics - c#

i need to check if a worksheet exist in excel and if not, to create it. I'm using infragistics and the following code gives me the following error:
use of unassigned local variable 'workSheet'.
this is the code:
Workbook workbook = new Workbook();
Worksheet workSheet;
foreach (Something result in results)
{
foreach (Something item in result.Something)
{
if (!workbook.Worksheets.Exists(item.GetType().Name))
{
workSheet = workbook.Worksheets.Add(item.GetType().Name);
}
// cell font
IWorkbookFont oFont = workSheet.Workbook.CreateNewWorkbookFont();
....
}
}
The error is about the: IWorkbookFont oFont = workSheet.Workbook.CreateNewWorkbookFont()
on the workSheet variable.
thanks.

Here is how you can avoid the error. Initialize worksheet to null when you declare it. Do not forget the null check before accessing the worksheet.
Workbook workbook = new Workbook();
Worksheet workSheet = null;
foreach (Something result in results)
{
foreach (Something item in result.Something)
{
if (!workbook.Worksheets.Exists(item.GetType().Name))
{
workSheet = workbook.Worksheets.Add(item.GetType().Name);
}
if (workSheet != null)
{
// cell font
IWorkbookFont oFont = workSheet.Workbook.CreateNewWorkbookFont();
....
}
....
}
}

I've found the answer:
Worksheet workSheet = null;
if (!workbook.Worksheets.Exists(item.GetType().Name))
{
workSheet = workbook.Worksheets.Add(item.GetType().Name);
}
else
{
workSheet = workbook.Worksheets[item.GetType().Name];
}
// cell font
IWorkbookFont oFont = workSheet.Workbook.CreateNewWorkbookFont();
I had to make sure the workSheet variable has values (initialized).

Related

Change MS Excel Row Colour in Excel using C#

I am currently creating a small program that will allow a user to input data into a windows form. Once this data has been input into the form it will then be added to a Excel Document using OleDb.
I have no problems with the above section and I can input data no bother however my problem comes when I try to change the colour of the Excel Row.
I am looking to change the colour of the row to red if the row currently has no fill.
The code I am currently using:
Excel.Application application = new Excel.Application();
Excel.Workbook workbook = application.Workbooks.Open(#"C:\Users\jhughes\Desktop\ScreenUpdate.xls");
Excel.Worksheet worksheet = (Excel.Worksheet)workbook.Sheets["DailyWork"];
Excel.Range usedRange = worksheet.UsedRange;
Excel.Range rows = usedRange.Rows;
try
{
foreach (Excel.Range row in rows)
{
if (row.Cells.EntireRow.Interior.ColorIndex = 0)
{
row.Interior.Color = System.Drawing.Color.Red;
}
}
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
I am getting the error "Cannot implicitly convert type int to bool" at the line "If(row.Cells.EntireRow....)"
You are attempting to set the ColorIndex to 0, not comparing it to 0. Use == when you compare.
foreach (Excel.Range row in rows)
{
if (row.Cells.EntireRow.Interior.ColorIndex == 0) // changed = to ==
{
row.Interior.Color = System.Drawing.Color.Red;
}
}
You need to use == operator instead of = operator. == operator for equality but = operator is for assignment.
if (row.Cells.EntireRow.Interior.ColorIndex == 0)
= operators simply assign right operand to the left variable/property/indexer and returns the value as its result. That's why when you write
if (row.Cells.EntireRow.Interior.ColorIndex = 0)
it is equal to
if(0)
which is won't compile since if statement expects boolean expression.
I think you not added saving to workbook and change in if condition. Somehow the default colorindex is coming as -4142. Tested now able to change the change color
Excel.Application application = new Excel.Application();
Excel.Workbook workbook = application.Workbooks.Open(#"C:\Users\MyPath\Desktop\ColorBook.xls");
Excel.Worksheet worksheet = (Excel.Worksheet)workbook.Sheets["DailyWork"];
Excel.Range usedRange = worksheet.UsedRange;
Excel.Range rows = usedRange.Rows;
try
{
foreach (Excel.Range row in rows)
{
if (row.Cells.EntireRow.Interior.ColorIndex == -4142)
{
row.Interior.Color = System.Drawing.Color.Red;
}
}
workbook.Save();
workbook.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}

How to create(export) excel file readonly using Open Xml 2.5 SDK

I am developing one WPF application (using MVVM). I am also able to export my List to Excel file.But my problem is I am not able to make it readonly, so no one can able to make changes afterwards.
document.WorkbookPart.Workbook.WorkbookProtection=new WorkbookProtection
{
LockStructure=true
};
I only found this, but it's only make workbook readonly
Here is my code for creating excel file
public static bool CreateExcelDocument(DataSet ds, string excelFilename)
{
try
{
using (SpreadsheetDocument document = SpreadsheetDocument.Create(excelFilename, SpreadsheetDocumentType.Workbook))
{
document.AddWorkbookPart();
document.WorkbookPart.Workbook = new DocumentFormat.OpenXml.Spreadsheet.Workbook();
document.WorkbookPart.Workbook.WorkbookProtection=new WorkbookProtection
{
LockStructure = true,
};
// My thanks to James Miera for the following line of code (which prevents crashes in Excel 2010)
document.WorkbookPart.Workbook.Append(new BookViews(new WorkbookView()));
// If we don't add a "WorkbookStylesPart", OLEDB will refuse to connect to this .xlsx file !
WorkbookStylesPart workbookStylesPart = document.WorkbookPart.AddNewPart<WorkbookStylesPart>("rIdStyles");
Stylesheet stylesheet = new Stylesheet();
workbookStylesPart.Stylesheet = stylesheet;
CreateParts(ds, document);
}
Trace.WriteLine("Successfully created: " + excelFilename);
return true;
}
catch (Exception ex)
{
Trace.WriteLine("Failed, exception thrown: " + ex.Message);
return false;
}
}
private static void CreateParts(DataSet ds, SpreadsheetDocument spreadsheet)
{
// Loop through each of the DataTables in our DataSet, and create a new Excel Worksheet for each.
uint worksheetNumber = 1;
foreach (DataTable dt in ds.Tables)
{
// For each worksheet you want to create
string workSheetID = "rId" + worksheetNumber.ToString();
string worksheetName = dt.TableName;
WorksheetPart newWorksheetPart = spreadsheet.WorkbookPart.AddNewPart<WorksheetPart>();
newWorksheetPart.Worksheet = new DocumentFormat.OpenXml.Spreadsheet.Worksheet();
// create sheet data
newWorksheetPart.Worksheet.AppendChild(new DocumentFormat.OpenXml.Spreadsheet.SheetData());
// save worksheet
WriteDataTableToExcelWorksheet(dt, newWorksheetPart);
newWorksheetPart.Worksheet.Save();
// create the worksheet to workbook relation
if (worksheetNumber == 1)
spreadsheet.WorkbookPart.Workbook.AppendChild(new DocumentFormat.OpenXml.Spreadsheet.Sheets());
spreadsheet.WorkbookPart.Workbook.GetFirstChild<DocumentFormat.OpenXml.Spreadsheet.Sheets>().AppendChild(new DocumentFormat.OpenXml.Spreadsheet.Sheet()
{
Id = spreadsheet.WorkbookPart.GetIdOfPart(newWorksheetPart),
SheetId = (uint)worksheetNumber,
Name = dt.TableName
});
worksheetNumber++;
}
spreadsheet.WorkbookPart.Workbook.Save();
}
Before you open Excel, you can Lock your file with:
FileInfo cInfo = new FileInfo(Path);
cInfo.IsReadonly = true;
Than it will be readonly.

DateTimePicker value from Excel

I am wondering if it is possible to set the value of a DateTimePicker from a queried row in excel. I have tried different ways of doing it but have never came close and anyone help?
Also it all is displayed on a windows form
public void ReadAndWriteToExcel()
{
string myPath = #"C:\Excel.xls";
FileInfo fi = new FileInfo(myPath);
if (!fi.Exists)
{
Console.Out.WriteLine("file doesn't exists!");
}
else
{
var excelApp = new Microsoft.Office.Interop.Excel.Application();
var workbook = excelApp.Workbooks.Open(myPath);
Worksheet worksheet = workbook.ActiveSheet as Worksheet;
// To write to excel
Microsoft.Office.Interop.Excel.Range range = worksheet.Cells[1, 1] as Range;
DateTime dt = dateTimePicker1.Value;
range.NumberFormat = "dd/MMM/yyyy";
range.Value2 = dt;
// To read,
var date = worksheet.Cells[1, 1].Value;
Console.Out.WriteLine(date.ToString());
workbook.Save();
workbook.Close();
}
}
you must add "Microsoft.Office.Core" and "Microsoft.Office.Interop.Excel" references to your project and use them.

How to check if the Worksheet already exist in Interop

I want to check if the sheet exists before creating it.
using Excel = Microsoft.Office.Interop.Excel;
Excel.Application excel = new Excel.Application();
excel.Visible = true;
Excel.Workbook wb = excel.Workbooks.Open(#"C:\"Example".xlsx");
Excel.Worksheet sh = wb.Sheets.Add();
int count = wb.Sheets.Count;
sh.Name = "Example";
sh.Cells[1, "A"].Value2 = "Example";
sh.Cells[1, "B"].Value2 = "Example"
wb.Close(true);
excel.Quit();
This extension method returns the worksheet if it exists, null otherwise:
public static class WorkbookExtensions
{
public static Excel.Worksheet GetWorksheetByName(this Excel.Workbook workbook, string name)
{
return workbook.Worksheets.OfType<Excel.Worksheet>().FirstOrDefault(ws => ws.Name == name);
}
}
The linq method .Any() can be used instead of FirstOrDefault to check whether the worksheet exists as well...
Create a loop like this:
// Keeping track
bool found = false;
// Loop through all worksheets in the workbook
foreach(Excel.Worksheet sheet in wb.Sheets)
{
// Check the name of the current sheet
if (sheet.Name == "Example")
{
found = true;
break; // Exit the loop now
}
}
if (found)
{
// Reference it by name
Worksheet mySheet = wb.Sheets["Example"];
}
else
{
// Create it
}
I'm not into Office Interop very much, but come to think of it, you could also try the following, much shorter way:
Worksheet mySheet;
mySheet = wb.Sheets["NameImLookingFor"];
if (mySheet == null)
// Create a new sheet
But I'm not sure if that would simply return null without throwing an exception; you would have to try the second method for yourself.
Why not just do this:
try {
Excel.Worksheet wks = wkb.Worksheets["Example"];
} catch (System.Runtime.InteropServices.COMException) {
// Create the worksheet
}
wks.Select();
The other way avoids throwing and catching exceptions, and certainly it's a legitimate answer, but I found this and wanted to put this up as an alternative.

Read first line of XLS without specific sheet name

I've found how to read first line from Excel file with specific sheet name, but in my case I have to read first line of the first sheet.
How can I realize that or I have to use CSV instead of XLS?
Did you take a look at the EPPlus library? It makes very easy to work with excel files.
Here is how you would do that using EPPlus:
FileInfo existingFile = new FileInfo("yourfilepathname");
using (var package = new ExcelPackage(existingFile))
{
ExcelWorkbook workbook = package.Workbook;
if (workbook != null && workbook.Worksheets.Count > 0)
{
//Gets the first worksheet. You can use index also to select your worksheet.
ExcelWorksheet worksheet = workbook.Worksheets.First();
int rowIndex = 0;
int colIndex = 0;
//To get the first cell:
var cellValue = worksheet.Cells[rowIndex, colIndex].Value;
//YOU CAN ALSO DO A LOOP TO GET ALL VALUES FROM THE FIRST ROW.
}
}
NPOI is another good option and it can handle XLS files too.
Here's a snippet of NPOI code:
HSSFWorkbook _hssfworkbook = new HSSFWorkbook(OpenFileStream(filePath));
//Getting the sheet
_currentSheet = _hssfworkbook.GetSheetAt(0);
//Getting the row:
_row = CurrentSheet.GetRow(0);
//Getting the cell
_cell = _row.GetCell(0);
Have you considered SpreadsheetLight? Here's how you do it:
SLDocument sl = new SLDocument("YourExcelFile.xlsx", "TheSheetName");
string FirstLine = sl.GetCellValueAsString("A1");
sl.CloseWithoutSaving();
Disclaimer: I wrote SpreadsheetLight.

Categories

Resources