RubyXL : How can I make a cell as dropdown in XLSX - rubyxl

I am using RubyXL gem to read and write a xlsm file.In my project there is a field Country which should diplay all list of countries in a dropdown in xlsm.I have tried with DataValidation but when I tried to open the file it is showing as 'We found a problem with some content in filename.xlsm.Do you want to try us to revcover as much as we can?' and if I clicked 'yes'it is not showing dropdown list on that cell.My code is given below.
workbook = RubyXL::Parser.parse(dest_file_path)
worksheet1 = workbook["Form"]
content = ['Afghanistan','Albania,'Algeria']
formula = RubyXL::Formula.new(expression: content)
loc = RubyXL::Reference.new(1, 1048000, 2, 2)
worksheet1.data_validations =
RubyXL::DataValidation.new(prompt_title: nil, prompt: nil,
sqref: loc, formula1: formula,
type: 'list', show_input_message: true,
show_drop_down: true)
How should I associate DataValidation to a specific worksheet ? Is there any other way I can do this? Could anyone please help.

RubyXL Data Validations are collection, wrapping your Data Validation in brackets should add appropriately add the data validations to worksheet1
workbook = RubyXL::Parser.parse(dest_file_path)
worksheet1 = workbook["Form"]
content = ['Afghanistan','Albania,'Algeria']
formula = RubyXL::Formula.new(expression: content)
loc = RubyXL::Reference.new(1, 1048000, 2, 2)
worksheet1.data_validations = [
RubyXL::DataValidation.new(prompt_title: nil, prompt: nil,
sqref: loc, formula1: formula,
type: 'list', show_input_message: true,
show_drop_down: true)]

Related

Can we use Cell Range Validation to populate a dropdown list in excel from another sheet in EPPLUS

I am new to using EPplus. I actually wanted to populate a dropdown list in Sheet1 from a list of values in Sheet2. This can be achieved by Cell Range Validation in Excel.But I am not sure whether EPPlus support this programmatically. It will be really helpful if anyone could help me out.
Populate a dropdown in this Designation Column from Designation Column in Sheet 2.
Sheet 2
Here's how to do it:
var departmentSheet = excel.Workbook.Worksheets.Add("department");
departmentSheet.Cells["A1"].Value = "Management";
departmentSheet.Cells["A2"].Value = "Administrator";
departmentSheet.Cells["A3"].Value = "Quality Engineering";
departmentSheet.Cells["A4"].Value = "Enablers";
var designationSheet = excel.Workbook.Worksheets.Add("designations");
designationSheet.Cells["A1"].Value = "Developer 1";
designationSheet.Cells["A2"].Value = "Developer 2";
designationSheet.Cells["A3"].Value = "Developer 3";
designationSheet.Cells["A4"].Value = "Developer 4";
// add a validation and set values
// the range of cells that will contain the validation
var validation = departmentSheet.DataValidations.AddListValidation("B1:B4");
// set validation rules as required
validation.ShowErrorMessage = true;
validation.ErrorStyle = ExcelDataValidationWarningStyle.warning;
validation.ErrorTitle = "An invalid value was entered";
validation.Error = "Select a value from the list";
// set the range that contains the validation list
validation.Formula.ExcelFormula = $"={ designationSheet.Name }!$A$1:$A$4";

How to write array in excel sheet using excel4node

I am creating an excel file by using Excel4node package.
by using this code
// Require library
var excel = require('excel4node');
// Create a new instance of a Workbook class
var workbook = new excel.Workbook();
// Add Worksheets to the workbook
var worksheet = workbook.addWorksheet('Sheet 1');
var worksheet2 = workbook.addWorksheet('Sheet 2');
// Create a reusable style
var style = workbook.createStyle({
font: {
color: '#FF0800',
size: 12
},
numberFormat: '$#,##0.00; ($#,##0.00); -'
});
// Set value of cell A1 to 100 as a number type styled with paramaters of style
worksheet.cell(1,1).number(100).style(style);
// Set value of cell B1 to 300 as a number type styled with paramaters of style
worksheet.cell(1,2).number(200).style(style);
// Set value of cell C1 to a formula styled with paramaters of style
worksheet.cell(1,3).formula('A1 + B1').style(style);
// Set value of cell A2 to 'string' styled with paramaters of style
worksheet.cell(2,1).string('string').style(style);
// Set value of cell A3 to true as a boolean type styled with paramaters of style but with an adjustment to the font size.
worksheet.cell(3,1).bool(true).style(style).style({font: {size: 14}});
workbook.write('Excel.xlsx');
by using this code creating an excel sheet now what I want is.
I want to write the array in the excel sheet.
worksheet.getCell('A1').value = 's.no';
by using the code. it is writing the data to the sheet but it is writing the data by cell by cell.
it takes to much of time to write the array in excel sheet
data=[{s.no:1,Name:'xxx',Age:'22'},
{s.no:2,Name:'yyy',Age:'12'},
{s.no:3,Name:'zzz',Age:'32'}]
I want to write the array in the excel sheet.
workbook.write('Excel.xlsx',data);
I given like this but this also not working.
can anyone resolve this.
why you don't use
sheet.cell(row , col ).string(`your value`).style(`your style`);
What I would do is create an excel4node layer. Something to the effect of:
// the type arg is the cell write method you want to use such as string, number, or formula
const writeCell(wb, ws, row, col, value, type, style){
ws.cell(row, col)[type](value).style(wb.createStyle(style))
}
const xl = require('excel4node')
const wb = xl.createWorkbook()
// TODO: track your row and column indices with arrays. let's assume that we are
// in the outer array and the inner array or row array is called "data"
// this would write out a row of data
data.forEach((d, idx) => {
writeCell(wb, ws, rowIdx, idx + 1, d.value, d.type, d.style)
}
const array_elements = [{
fullname: "name 1",
game1point: 10,
game2point: 12
},
{
fullname: "name 2",
game1point: 15,
game2point: 17
},
]
let startRow = 3;
for (let i = 0; i < array_elements.length; i++) {
// FULLNAME - FIRST COLUMN
worksheet.cell(startRow + i, 1).string(array_elements[i].fullname);
// SECOND COLUMN
worksheet.cell(startRow + i, 2).number(array_elements[i].game1point);
// THIRD COLUMN
worksheet.cell(startRow + i, 3).number(array_elements[i].game2point);
gameCol++;
}

How to find same values from different cell in Excel file using C#

Microsoft.Office.Interop.Excel.Range Range_Number_Phone;
Range_Number_Phone = xlWorkSheet.UsedRange.Find("Phone");
This code finds first values only.it can't find another word.How is it possible?Please help me.
using Free Spire.XLS dll from NuGet Package Manager we can find same values from a different cell.
Spire.Xls.Workbook workbook = new Spire.Xls.Workbook();
workbook.LoadFromFile(#"D:\\input.xlsx", ExcelVersion.Version2010);
//find and highlight excel data
Spire.Xls.Worksheet sheet = workbook.Worksheets[0];
foreach (CellRange range in sheet.FindAllString("Customer PO Number", false, false))
{
range.Style.Color = Color.LawnGreen;
}
//save and launch the project
workbook.SaveToFile("result.xlsx", ExcelVersion.Version2010);
System.Diagnostics.Process.Start("result.xlsx");

How to access a FormControl checkbox in an Excel sheet using OpenXML SDK

I have a spreadsheet that has a number of check boxes in various cells on the sheet that I need to get the value of (checked/unchecked) from within a c# program.
I'm using the OpenXML SDK v2.5 and the associated toolbox.
Using the toolbox I can see the check box controls as part of the AlternateControlParts collection. These are not ActiveX checkboxes but are form controls added via the developer tab in Excel.
When I use the SDK I can also see the WorkSheetPart which has a ControlPropertiesParts collection on it which lists all the checkboxes.
My problem is, how do I find which checkbox is in which cell or at least related to which cell?
I have also found the collection
wsPart.ControlPropertiesParts.First().DrawingsPart
.WorkSheetDrawing.DrawingsPart.WorkSheetDrawing
This collection appears to have the alternate content of each of the checkboxes and if I drill down further I can find the anchor points which appear to give the location of the checkboxes relative to the cells on the sheet. However, the col and row Id’s don’t appear to exactly match up and I suspect that the Offset values may also have something to do with it.
If someone can point me in the right direction on how to map the checkboxes to the correct row/cells I would be very grateful.
Thank you for any help.
Regards
Paul
I have a solution, it contains only the logic (The property FormControlProperties is available since Office 2010:
SpreadsheetDocument document;
string sheetName = "sheetName";
string controlName = "Option Button 5";
...
var wbPart = document.WorkbookPart;
var theSheet = wbPart.Workbook.Descendants<Sheet>().FirstOrDefault(s => s.Name == sheetName);
var wsPart = (WorksheetPart)wbPart.GetPartById(theSheet.Id);
var control = wsPart.Worksheet.Descendants<DocumentFormat.OpenXml.Spreadsheet.Control>().FirstOrDefault(c => c.Name == controlName);
var controlProperies = (ControlPropertiesPart)wsPart.GetPartById(control.Id);
bool isChecked = controlProperies.FormControlProperties.Checked == "Checked";
But it is simplier to map the FormControl value to a cell and read the cell value if the you can edit the excel file.

Why is my "defined name" (range) value not being set with this Spreadsheet Light code?

I've got this code to apply a "header" (big, top-of-the-sheet "title") to a sheet:
// Initialize
private static SLDocument sl;
. . .
sl = new SLDocument();
// Create a Style
SLStyle styleHeading = sl.CreateStyle();
styleHeading.SetFont(FontSchemeValues.Major, 36);
styleHeading.Font.Italic = true;
styleHeading.Font.FontName = "Candara";
// Create a Defined Name (Range) and give it a value and style
sl.SetDefinedName("UnitName", "Sheet1!$A$1:$A$13");
sl.SetCellValue("UnitName", "Pennsylvania Platypi Presumptuously Parasailing");
sl.SetCellStyle("UnitName", styleHeading);
// Save the sheet
string appDataFolder = HttpContext.Current.Server.MapPath("~/App_Data/");
string spreadsheetLightFilename = "PlatypiTest.xlsx";
string fullspreadsheetLightPath = Path.Combine(appDataFolder, spreadsheetLightFilename);
sl.SaveAs(fullspreadsheetLightPath);
Note: I verified that "Sheet1" was right with this code:
var nameList = sl.GetSheetNames();
string s = nameList[0]; // "s" is "Sheet1"
The file is created and saved, but it is devoid of content; when I open it, cell A1 is highlighted, but is content-free.
Am I missing a vital step, or going about this completely wrong?
What are you doing is logically fine.
This line
sl.SetDefinedName("UnitName", "Sheet1!$A$1:$A$13");
indeed creates a named range. You can see it if you open the resulting file in Excel and look at the cell selector:
or the Name Manager:
The problem is though that Spreadsheet Light has a very basic support for Defined names - basically all you can do is to create a name and use it inside the formulas. All methods that manipulate content expect single cell reference. Btw, all these methods do not throw exception if you don't pass a valid cell reference, but return bool indicating success/failure.
For instance, if you change your code to
bool success1 = sl.SetCellValue("UnitName", "Pennsylvania Platypi Presumptuously Parasailing");
bool success2 = sl.SetCellStyle("UnitName", styleHeading);
you will see that both success variables are false.
Shortly, if you want to bring some content to the Excel file, you should do it cell by cell. It even does not support regular (unnamed) ranges.
Theoretically, at least, you could do it this way:
// from http://stackoverflow.com/questions/36481802/what-is-the-analogue-to-excel-interops-worksheet-usedrange-rows-in-spreadsheet
var stats = sl.GetWorksheetStatistics();
var rowcount = stats.NumberOfRows;
SLStyle entireSheetRangeStyle = sl.CreateStyle();
entireSheetRangeStyle.// (set style vals)
. . .
sl.SetRowStyle(1, rowcount, entireSheetRangeStyle);

Resources