Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove/Rename default sheet, also add color helper #319

Merged
merged 10 commits into from
Feb 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion example/excel_border.dart
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ void main(List<String> args) {
CellIndex.indexByColumnRow(columnIndex: 5, rowIndex: 10));

Border border = Border(
borderColorHex: "#FF000000",
borderColorHex: "#FF000000".excelColor,
borderStyle: BorderStyle.Thin,
);

Expand Down
72 changes: 72 additions & 0 deletions example/excel_save.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import 'dart:io';

import 'package:excel/excel.dart';

void main() {
final excel = Excel.createExcel();

const defaultSheetName = 'Sheet1';
const testSheetToKeep = 'Sheet To Keep';
const testSheetToKeepRename = 'Rename Of Sheet To Keep';

var listDynamic = (List<List<dynamic>>.generate(
5, (_) => List<int>.generate(5, (i) => i + 1))
..insert(0, [
'A',
'B',
'C',
'D',
'E',
]));

for (var row = 0; row < listDynamic.length; row++) {
for (var column = 0; column < listDynamic[row].length; column++) {
final cellIndex = CellIndex.indexByColumnRow(
columnIndex: column,
rowIndex: row,
);
var colorList = List.of(ExcelColor.values);
final border = Border(
borderColorHex: (colorList..shuffle()).first,
borderStyle: BorderStyle.Thin);

final string = listDynamic[row][column].toString();

var cellValue = int.tryParse(string) != null
? IntCellValue(int.parse(string))
: TextCellValue(string);

excel.updateCell(
testSheetToKeep,
cellIndex,
cellValue,
cellStyle: CellStyle()
..backgroundColor = (colorList..shuffle()).first
..topBorder = border
..bottomBorder = border
..leftBorder = border
..rightBorder = border
..fontColor = (colorList..shuffle()).first
..fontFamily = 'Arial',
);
}
}

///
assert(excel.sheets.keys.contains(defaultSheetName));
assert(excel.getDefaultSheet() == defaultSheetName);
excel.delete(excel.getDefaultSheet()!);
assert(!excel.sheets.keys.contains(defaultSheetName));

///
excel.rename(testSheetToKeep, testSheetToKeepRename);
excel.setDefaultSheet(testSheetToKeepRename);
assert(excel.getDefaultSheet() == testSheetToKeepRename);

final bytes = excel.encode();
if (bytes != null) {
File('example/example.xlsx')
..createSync()
..writeAsBytesSync(bytes);
}
}
2 changes: 2 additions & 0 deletions lib/excel.dart
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ part 'src/utilities/fast_list.dart';
part 'src/utilities/utility.dart';
part 'src/utilities/constants.dart';
part 'src/utilities/enum.dart';
part 'src/utilities/archive.dart';
part 'src/utilities/colors.dart';

/// Save
part 'src/save/save_file.dart';
Expand Down
20 changes: 14 additions & 6 deletions lib/src/excel.dart
Original file line number Diff line number Diff line change
Expand Up @@ -274,18 +274,26 @@ class Excel {
_sheetName.getAttribute('PartName') == '/' + sheetId2;
});

///
/// Remove from the `_archive` also
_archive.files.removeWhere((file) {
return file.name.toLowerCase() == _xmlSheetId[sheet]?.toLowerCase();
});

///
/// Also remove from the _xmlFiles list as we might want to create this sheet again from new starting.
if (_xmlFiles[_xmlSheetId[sheet]] != null) {
_xmlFiles.remove(_xmlSheetId[sheet]);
}

///
/// Maybe overkill and unsafe to do this, but works for now especially
/// delete or renaming default sheet name (`Sheet1`),
/// another safer method preferred
_archive = _cloneArchive(
_archive,
_xmlFiles.map((k, v) {
final encode = utf8.encode(v.toString());
final value = ArchiveFile(k, encode.length, encode);
return MapEntry(k, value);
}),
excludedFile: _xmlSheetId[sheet],
);

_xmlSheetId.remove(sheet);
}

Expand Down
35 changes: 20 additions & 15 deletions lib/src/parser/parse.dart
Original file line number Diff line number Diff line change
Expand Up @@ -276,8 +276,9 @@ class Parser {
borderColorHex = color?.getAttribute('rgb')?.trim();
} on StateError catch (_) {}

borderElements[elementName] =
Border(borderStyle: borderStyle, borderColorHex: borderColorHex);
borderElements[elementName] = Border(
borderStyle: borderStyle,
borderColorHex: borderColorHex?.excelColor);
}

final borderSet = _BorderSet(
Expand Down Expand Up @@ -311,7 +312,8 @@ class Parser {
final numFmtId = _getFontIndex(node, 'numFmtId');
_excel._numFmtIds.add(numFmtId);

String fontColor = "FF000000", backgroundColor = "none";
String fontColor = ExcelColor.black.colorHex,
backgroundColor = ExcelColor.none.colorHex;
String? fontFamily;
FontScheme fontScheme = FontScheme.Unset;
_BorderSet? borderSet;
Expand Down Expand Up @@ -384,7 +386,7 @@ class Parser {
_fontStyle.fontSize = fontSize;
_fontStyle.fontFamily = fontFamily;
_fontStyle.fontScheme = fontScheme;
_fontStyle._fontColorHex = fontColor;
_fontStyle._fontColorHex = fontColor.excelColor;
}

/// If `-1` is returned then it indicates that `_fontStyle` is not present in the `_fontStyleList`
Expand Down Expand Up @@ -437,18 +439,21 @@ class Parser {

var numFormat = _excel._numFormats.getByNumFmtId(numFmtId);
if (numFormat == null) {
assert(false, 'missing numFmt for ${numFmtId}');
assert(false, 'missing numFmt for $numFmtId');
numFormat = NumFormat.standard_0;
}

CellStyle cellStyle = CellStyle(
fontColorHex: fontColor,
fontColorHex: fontColor.excelColor,
fontFamily: fontFamily,
fontSize: fontSize,
bold: isBold,
italic: isItalic,
underline: underline,
backgroundColorHex: backgroundColor,
backgroundColorHex:
backgroundColor == 'none' || backgroundColor.isEmpty
? ExcelColor.none
: backgroundColor.excelColor,
horizontalAlign: horizontalAlign,
verticalAlign: verticalAlign,
textWrapping: textWrapping,
Expand Down Expand Up @@ -719,7 +724,7 @@ class Parser {
.add(XmlElement(XmlName('Relationship'), <XmlAttribute>[
XmlAttribute(XmlName('Id'), 'rId$ridNumber'),
XmlAttribute(XmlName('Type'), '$_relationships/worksheet'),
XmlAttribute(XmlName('Target'), 'worksheets/sheet${sheetNumber}.xml'),
XmlAttribute(XmlName('Target'), 'worksheets/sheet$sheetNumber.xml'),
]));

if (!_rId.contains('rId$ridNumber')) {
Expand All @@ -735,25 +740,25 @@ class Parser {
<XmlAttribute>[
XmlAttribute(XmlName('state'), 'visible'),
XmlAttribute(XmlName('name'), newSheet),
XmlAttribute(XmlName('sheetId'), '${sheetNumber}'),
XmlAttribute(XmlName('sheetId'), '$sheetNumber'),
XmlAttribute(XmlName('r:id'), 'rId$ridNumber')
],
));

_worksheetTargets['rId$ridNumber'] = 'worksheets/sheet${sheetNumber}.xml';
_worksheetTargets['rId$ridNumber'] = 'worksheets/sheet$sheetNumber.xml';

var content = utf8.encode(
"<worksheet xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\" xmlns:mc=\"http://schemas.openxmlformats.org/markup-compatibility/2006\" mc:Ignorable=\"x14ac xr xr2 xr3\" xmlns:x14ac=\"http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac\" xmlns:xr=\"http://schemas.microsoft.com/office/spreadsheetml/2014/revision\" xmlns:xr2=\"http://schemas.microsoft.com/office/spreadsheetml/2015/revision2\" xmlns:xr3=\"http://schemas.microsoft.com/office/spreadsheetml/2016/revision3\"> <dimension ref=\"A1\"/> <sheetViews> <sheetView workbookViewId=\"0\"/> </sheetViews> <sheetData/> <pageMargins left=\"0.7\" right=\"0.7\" top=\"0.75\" bottom=\"0.75\" header=\"0.3\" footer=\"0.3\"/> </worksheet>");

_excel._archive.addFile(ArchiveFile(
'xl/worksheets/sheet${sheetNumber}.xml', content.length, content));
'xl/worksheets/sheet$sheetNumber.xml', content.length, content));
var _newSheet =
_excel._archive.findFile('xl/worksheets/sheet${sheetNumber}.xml');
_excel._archive.findFile('xl/worksheets/sheet$sheetNumber.xml');

_newSheet!.decompress();
var document = XmlDocument.parse(utf8.decode(_newSheet.content));
_excel._xmlFiles['xl/worksheets/sheet${sheetNumber}.xml'] = document;
_excel._xmlSheetId[newSheet] = 'xl/worksheets/sheet${sheetNumber}.xml';
_excel._xmlFiles['xl/worksheets/sheet$sheetNumber.xml'] = document;
_excel._xmlSheetId[newSheet] = 'xl/worksheets/sheet$sheetNumber.xml';

_excel._xmlFiles['[Content_Types].xml']
?.findAllElements('Types')
Expand All @@ -765,7 +770,7 @@ class Parser {
XmlAttribute(XmlName('ContentType'),
'application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml'),
XmlAttribute(
XmlName('PartName'), '/xl/worksheets/sheet${sheetNumber}.xml'),
XmlName('PartName'), '/xl/worksheets/sheet$sheetNumber.xml'),
],
));
if (_excel._xmlFiles['xl/workbook.xml'] != null) {
Expand Down
45 changes: 13 additions & 32 deletions lib/src/save/save_file.dart
Original file line number Diff line number Diff line change
Expand Up @@ -33,25 +33,6 @@ class Save {
return ((maxNumOfCharacters * 7.0 + 9.0) / 7.0 * 256).truncate() / 256;
}

Archive _cloneArchive(Archive archive) {
var clone = Archive();
archive.files.forEach((file) {
if (file.isFile) {
ArchiveFile copy;
if (_archiveFiles.containsKey(file.name)) {
copy = _archiveFiles[file.name]!;
} else {
var content = file.content as Uint8List;
var compress = !_noCompression.contains(file.name);
copy = ArchiveFile(file.name, content.length, content)
..compress = compress;
}
clone.addFile(copy);
}
});
return clone;
}

/* XmlElement _replaceCell(String sheet, XmlElement row, XmlElement lastCell,
int columnIndex, int rowIndex, CellValue? value) {
var index = lastCell == null ? 0 : row.children.indexOf(lastCell);
Expand Down Expand Up @@ -122,7 +103,7 @@ class Save {
final String v = switch (numberFormat) {
NumericNumFormat() => numberFormat.writeInt(value),
_ => throw Exception(
'${numberFormat} does not work for ${value.runtimeType}'),
'$numberFormat does not work for ${value.runtimeType}'),
};
children = [
XmlElement(XmlName('v'), [], [XmlText(v)]),
Expand All @@ -131,7 +112,7 @@ class Save {
final String v = switch (numberFormat) {
NumericNumFormat() => numberFormat.writeDouble(value),
_ => throw Exception(
'${numberFormat} does not work for ${value.runtimeType}'),
'$numberFormat does not work for ${value.runtimeType}'),
};
children = [
XmlElement(XmlName('v'), [], [XmlText(v)]),
Expand All @@ -140,7 +121,7 @@ class Save {
final String v = switch (numberFormat) {
DateTimeNumFormat() => numberFormat.writeDateTime(value),
_ => throw Exception(
'${numberFormat} does not work for ${value.runtimeType}'),
'$numberFormat does not work for ${value.runtimeType}'),
};
children = [
XmlElement(XmlName('v'), [], [XmlText(v)]),
Expand All @@ -149,7 +130,7 @@ class Save {
final String v = switch (numberFormat) {
DateTimeNumFormat() => numberFormat.writeDate(value),
_ => throw Exception(
'${numberFormat} does not work for ${value.runtimeType}'),
'$numberFormat does not work for ${value.runtimeType}'),
};
children = [
XmlElement(XmlName('v'), [], [XmlText(v)]),
Expand All @@ -158,7 +139,7 @@ class Save {
final String v = switch (numberFormat) {
TimeNumFormat() => numberFormat.writeTime(value),
_ => throw Exception(
'${numberFormat} does not work for ${value.runtimeType}'),
'$numberFormat does not work for ${value.runtimeType}'),
};
children = [
XmlElement(XmlName('v'), [], [XmlText(v)]),
Expand Down Expand Up @@ -226,7 +207,7 @@ class Save {
}

/// Filling the inner usable extra list of background color
String backgroundColor = cellStyle.backgroundColor;
String backgroundColor = cellStyle.backgroundColor.colorHex;
if (!_excel._patternFill.contains(backgroundColor) &&
!innerPatternFill.contains(backgroundColor)) {
innerPatternFill.add(backgroundColor);
Expand Down Expand Up @@ -255,11 +236,11 @@ class Save {
fonts.children.add(XmlElement(XmlName('font'), [], [
/// putting color
if (fontStyleElement._fontColorHex != null &&
fontStyleElement._fontColorHex != "FF000000")
XmlElement(
XmlName('color'),
[XmlAttribute(XmlName('rgb'), fontStyleElement._fontColorHex!)],
[]),
fontStyleElement._fontColorHex!.colorHex != "FF000000")
XmlElement(XmlName('color'), [
XmlAttribute(
XmlName('rgb'), fontStyleElement._fontColorHex!.colorHex)
], []),

/// putting bold
if (fontStyleElement.isBold) XmlElement(XmlName('b'), [], []),
Expand Down Expand Up @@ -410,7 +391,7 @@ class Save {
}

_innerCellStyle.forEach((cellStyle) {
String backgroundColor = cellStyle.backgroundColor;
String backgroundColor = cellStyle.backgroundColor.colorHex;

_FontStyle _fs = _FontStyle(
bold: cellStyle.isBold,
Expand Down Expand Up @@ -572,7 +553,7 @@ class Save {
var content = utf8.encode(xml);
_archiveFiles[xmlFile] = ArchiveFile(xmlFile, content.length, content);
}
return ZipEncoder().encode(_cloneArchive(_excel._archive));
return ZipEncoder().encode(_cloneArchive(_excel._archive, _archiveFiles));
}

void _setColumns(Sheet sheetObject, XmlDocument xmlFile) {
Expand Down
7 changes: 4 additions & 3 deletions lib/src/sheet/border_style.dart
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,11 @@ class Border extends Equatable {
late final BorderStyle? borderStyle;
late final String? borderColorHex;

Border({BorderStyle? borderStyle, String? borderColorHex}) {
Border({BorderStyle? borderStyle, ExcelColor? borderColorHex}) {
this.borderStyle = borderStyle == BorderStyle.None ? null : borderStyle;
this.borderColorHex =
borderColorHex != null ? _isColorAppropriate(borderColorHex) : null;
this.borderColorHex = borderColorHex != null
? _isColorAppropriate(borderColorHex.colorHex)
: null;
}

@override
Expand Down
Loading
Loading