deleteColumn method
Delete the Column in the Worksheet.
// Create a new Excel Document.
final Workbook workbook = Workbook();
// Accessing sheet via index.
final Worksheet sheet = workbook.worksheets[0];
Range range = sheet.getRangeByName('A2');
range.setText('Hello');
range = sheet.getRangeByName('C2');
range.setText('World');
// Delete a column.
sheet.deleteColumn(2, 1);
// Save and dispose workbook.
final List<int> bytes = workbook.saveAsStream();
File('DeleteRowandColumn.xlsx').writeAsBytes(bytes);
workbook.dispose();
Implementation
void deleteColumn(int columnIndex, [int? columnCount]) {
if (columnIndex < 1 || columnIndex > workbook.maxColumnCount) {
throw Exception(
'Value cannot be less 1 and greater than max column index.');
}
columnCount ??= 1;
if (columnCount < 0) {
throw Exception('count');
}
final int firstRow = getFirstRow();
final int lastRow = getLastRow();
final int lastColumn = getLastColumn();
for (int i = firstRow; i <= lastRow; i++) {
if (rows[i] != null) {
for (int count = 1; count <= columnCount; count++) {
for (int j = columnIndex; j <= lastColumn; j++) {
final Range? range = rows[i]!.ranges[j];
if (range != null &&
j != lastColumn &&
rows[i]!.ranges[j + 1] != null) {
rows[i]!.ranges[j] = rows[i]!.ranges[j + 1];
rows[i]!.ranges[j]!.index = rows[i]!.ranges[j]!.index - 1;
rows[i]!.ranges[j]!.row = rows[i]!.ranges[j]!.row;
rows[i]!.ranges[j]!.lastRow = rows[i]!.ranges[j]!.lastRow;
rows[i]!.ranges[j]!.column = rows[i]!.ranges[j]!.column - 1;
rows[i]!.ranges[j]!.lastColumn =
rows[i]!.ranges[j]!.lastColumn - 1;
} else if (range == null &&
j != lastColumn &&
rows[i]!.ranges[j + 1] != null) {
rows[i]!.ranges[j] = Range(this);
rows[i]!.ranges[j] = rows[i]!.ranges[j + 1];
rows[i]!.ranges[j]!.index = rows[i]!.ranges[j]!.index - 1;
rows[i]!.ranges[j]!.row = rows[i]!.ranges[j]!.row;
rows[i]!.ranges[j]!.lastRow = rows[i]!.ranges[j]!.lastRow;
rows[i]!.ranges[j]!.column = rows[i]!.ranges[j]!.column - 1;
rows[i]!.ranges[j]!.lastColumn =
rows[i]!.ranges[j]!.lastColumn - 1;
} else if (j == lastColumn &&
rows[i]!.ranges[j] == rows[i]!.ranges[lastColumn]) {
rows[i]!.ranges[j] = null;
} else {
rows[i]!.ranges[j] = rows[i]!.ranges[j + 1];
}
}
}
}
}
for (int count = 1; count <= columnCount; count++) {
for (int j = columnIndex; j <= lastColumn + columnCount; j++) {
if (columns[j] == null && columns[j + 1] == null) {
columns[j + 1] = Column(this);
columns[j + 1]!.index = j + 1;
columns[j] = Column(this);
columns[j]!.index = j;
}
if (columns[j] == null && columns[j + 1] != null) {
columns[j] = Column(this);
columns[j]!.index = j;
columns[j]!.width = columns[j + 1]!.width;
}
if (columns[j] != null && columns[j + 1] == null) {
columns[j + 1] = Column(this);
columns[j + 1]!.index = j + 1;
columns[j]!.width = columns[j + 1]!.width;
} else {
columns[j]!.width = columns[j + 1]!.width;
}
}
}
}