Is it possible to fetch the data existing in a file.xlsx using Excel dependency by columns?
I mean for each column that exist in the sheet it should be stored in a list for example.
I have only found how to fetch data by rows using:
for (var table in excel.tables.keys) {
for (var row in excel.tables[table].rows) {
// code
}
}
Is there any way to do this by columns?
Thank you.
I think this code from example is you need:
/// Iterating and changing values to desired type
for (int row = 0; row < sheet.maxRows; row++) {
sheet.row(row).forEach((cell) {
var val = cell.value; // Value stored in the particular cell
});
}
Found a temporary solution, downside is that you need to get column heading(s) for getting their values, below is the code if it helps you out:
Future<List<ExcelSheetData>> getExcelFile(BuildContext context, String name, String email) async {
FilePickerResult pickedFile = await FilePicker.platform.pickFiles(
type: FileType.custom,
allowedExtensions: ['xlsx'],
allowMultiple: false,
);
List<ExcelSheetData> excelList = [];
int nameIndex;
int emailIndex;
if (pickedFile != null) {
setAddMembersLoadingTrue();
var file = pickedFile.paths.single;
var bytes = await File(file).readAsBytes();
Excel excel = await compute(parseExcelFile, bytes);
for (var table in excel.tables.keys) {
for (var row in excel.tables[table].rows) {
// name variable is for Name of Column Heading for Name
if (row?.any((element) => element?.value?.toString() == name) ?? false) {
Data data = row?.firstWhere((element) => element?.value?.toString()?.toLowerCase() == name);
nameIndex = data.colIndex;
}
// email variable is for Name of Column Heading for Email
if (row?.any((element) => element?.value?.toString() == email) ?? false) {
Data data = row?.firstWhere((element) => element?.value?.toString()?.toLowerCase() == email);
emailIndex = data.colIndex;
}
if (nameIndex != null && emailIndex != null) {
if (row[nameIndex]?.value.toString().toLowerCase() != name.toLowerCase() && row[emailIndex]?.value.toString().toLowerCase() != email.toLowerCase())
excelList.add(
ExcelSheetData(
name: row[nameIndex]?.value.toString(),
email: row[emailIndex]?.value.toString(),
),
);
}
}
}
setAddMembersLoadingFalse();
return excelList;
}
return null;
}
refer to this question if you need more clarification
Related
I'm trying to handle some data for a flutter application, however I am getting the following error on my code:
The method 'add' can't be unconditionally invoked because the receiver can be 'null'. Try making the call conditional (using '?.') or adding a null check to the target ('!').
Map<String, List<SourcefulListing>> sortedSkills = {};
QuerySnapshot listingSnapshot = await listingsRef.get();
List<SourcefulListing> listings = [];
for (int i = 0; i < listingSnapshot.docs.length; i++) {
listings.add(SourcefulListing.fromJson(
listingSnapshot.docs[i].data() as Map<String, dynamic>));
}
for (String skill in skills) {
for (SourcefulListing listing in listings) {
if (listing.selectedSkill == skill) {
if (sortedSkills[skill] == null || sortedSkills[skill] != []) {
sortedSkills[skill] = [listing];
} else {
sortedSkills[skill] = sortedSkills[skill].add(listing);
}
}
}
}
Basically I have a Map with Strings as key and List for the values. The for each loop should add the SourcefulListing object to the map, however there is an error on the .add method.
Any help would be much appreciated.
Try this,
Map<String, List<SourcefulListing>> sortedSkills = {};
QuerySnapshot listingSnapshot = await listingsRef.get();
List<SourcefulListing> listings = [];
for (int i = 0; i < listingSnapshot.docs.length; i++) {
listings.add(SourcefulListing.fromJson(
listingSnapshot.docs[i].data() as Map<String, dynamic>));
}
for (String skill in skills) {
for (SourcefulListing listing in listings) {
if (listing.selectedSkill == skill) {
if (sortedSkills[skill] == null || sortedSkills[skill] != []) {
sortedSkills[skill] = [listing];
} else {
sortedSkills[skill]?.add(listing); // changes made here
setState(() {}); // update ui
}
}
}
}
Null Safety : https://dart.dev/null-safety
I want to update multiple rows in ASP.NET Core, but I get an error:
InvalidOperationException: The entity type 'EntityQueryable' was not found. Ensure that the entity type has been added to the model.
This is my code:
var data = _db.UserTable.Where(a => a.CityIDn == selectedid);
foreach (var items in data)
{
await Task.Run(() =>
{
items.CityID = 2;
});
_db.Update(data);
await _db.SaveChangesAsync();
}
Try this for multiple rows:
var data = _db.UserTable.Where(a => a.CityIDn == selectedid).ToList();
foreach (var item in data)
{
item.CityID = 2;
_db.UserTable.Update(item);
}
await _db.SaveChangesAsync();
And for one record, try like this:
var data = _db.UserTable.Where(a => a.CityIDn == selectedid).FirstOrDefault();
if(data != null)
{
data.CityID = 2;
_db.UserTable.Update(data );
await _db.SaveChangesAsync();
}
The content of Update should be items, it worked for me, you can have a try.
var data = _db.UserTable.Where(a => a.CityIDn == selectedid).ToList();
foreach (var items in data)
{
await Task.Run(() =>
{
items.CityID = 2;
});
_db.Update(items);
await _db.SaveChangesAsync();
}
How to determine whether a list is bulleted or numbered? I use OpenXML
In general, what will be the list determines NumberingDefinitionsPart, I thought to find out the Numbering of a certain element, but this method did not work
I am processing the list in the recommended way, but I need to know which way it is
`public void ParagraphHandle(Elements.Paragraph paragraph, StringBuilder text)
{
var docPart = paragraph.DocumentPart;
var element = paragraph.Element;
var r = element.Descendants<Numbering>().ToArray();
var images = GetImages(docPart, element);
if (images.Count > 0)
{
foreach (var image in images)
{
if (image.Id != null)
{
string filePath = _saveResources.SaveImage(image);
_handler.ImageHandle(filePath, text);
}
}
return;
}
var paragraphProperties = element.GetFirstChild<ParagraphProperties>();
var numberingProperties = paragraphProperties?.GetFirstChild<NumberingProperties>();
if (numberingProperties != null)
{
var numberingId = numberingProperties.GetFirstChild<NumberingId>()?.Val?.Value;
if (numberingId != null && !paragraph.IsList)
{
text.AppendLine("<ul>");
paragraph.IsList = true;
paragraph.List = new List();
_htmlGenerator.GenerateList(paragraph, text);
}
else
{
_htmlGenerator.GenerateList(paragraph, text);
}
}
else
{
if (paragraph.IsList)
{
text.AppendLine("</ul>");
paragraph.IsList = false;
}
_handler.ParagraphHandle(element, text);
}
}`
I have model Like This :
Model
class ActivityModel {
String idActivity;
String titleActivity;
String dateTimeActivity;
int isDoneActivity;
int codeIconActivity;
String informationActivity;
String createdDateActivity;
ActivityModel({
this.idActivity,
this.titleActivity,
this.dateTimeActivity,
this.isDoneActivity,
this.codeIconActivity,
this.informationActivity,
this.createdDateActivity,
});
ActivityModel.fromSqflite(Map<String, dynamic> map)
: idActivity = map['id_activity'],
titleActivity = map['title_activity'],
dateTimeActivity = map['datetime_activity'],
isDoneActivity = map['is_done_activity'],
codeIconActivity = map['code_icon_activity'],
informationActivity = map['information_activity'],
createdDateActivity = map['created_date'];
Map<String, dynamic> toMapForSqflite() {
return {
'id_activity': this.idActivity,
'title_activity': this.titleActivity,
'datetime_activity': this.dateTimeActivity,
'is_done_activity': this.isDoneActivity,
'code_icon_activity': this.codeIconActivity,
'information_activity': this.informationActivity,
'created_date': this.createdDateActivity,
};
}
I want get data where dateTimeActivity is before than date now, then i update isDoneActivity = 1 with this code :
Source code
final passedDateItem = _selectedActivityItem.where((element) {
DateTime convertStringToDateTime =
DateTime.parse(element.dateTimeActivity);
return convertStringToDateTime.isBefore(DateTime.now());
});
if (passedDateItem != null) {
print('Not Null');
} else {
print('Nulledd');
return null;
}
The problem is , passedDateItem return Iterable[ActivityModel] , it's possible to convert it to ActivityModel? So i can easly update like this ?
if (passedDateItem != null) {
passedDateItem.isDoneActivity = 1; <<<
// return passedDateItem.map((e) => e.isDoneActivity = 1);
// final testtt= passedDateItem.
print('Not Null');
} else {
print('Nulledd');
return null;
}
Iterate through passedDateItem
for (var activityModel in passedDateItem) {
//..conditions
activityModel.isDoneActivity = 1;
}
If you are only interested in the first/last element of passedDateItem
use
passedDateItem.first.isDoneActivity == 1
or
passedDateItem.last.isDoneActivity == 1
make sure passedDateItem is not empty in that case.
I am writing and extension for OpenXML like shown in the sample. I would like to avoid having to pass the WorkbookPart as parameter. Is there any way to get the WorkbookPart directly from the row?
public static string GetCellTextValue(this Row row, WorkbookPart workbookPart, string column)
{
var cells = row.Elements<Cell>();
var cell = cells.Where(p => p.CellReference == column + row.RowIndex.ToString()).FirstOrDefault();
if (cell.DataType != null)
{
if (cell.DataType == CellValues.SharedString)
{
int id = -1;
if (Int32.TryParse(cell.InnerText, out id))
{
SharedStringItem item = workbookPart.SharedStringTablePart.SharedStringTable.Elements<SharedStringItem>().ElementAt(id);
if (item.Text != null)
{
return item.Text.Text;
}
else if (item.InnerText != null)
{
return item.InnerText;
}
else if (item.InnerXml != null)
{
return item.InnerXml;
}
}
}
}
return string.Empty;
}
Unfortunately, none of the strongly-typed classes of the Open XML SDK (e.g., Workbook, Worksheet, Row) have properties pointing back to the OpenXmlPart (e.g., WorkbookPart, WorksheetPart) in which they are contained or any other part related to their immediate container. Unless you amend your API in other ways, you will have to pass that WorkbookPart.