| 1 |
# -*- coding: utf-8 -*- |
| 2 |
from __future__ import absolute_import, print_function, division |
| 3 |
|
| 4 |
import itertools |
| 5 |
|
| 6 |
from petl.compat import PY3, text_type |
| 7 |
from petl.util.base import Table, data |
| 8 |
from petl.io.sources import read_source_from_arg, write_source_from_arg |
| 9 |
|
| 10 |
|
| 11 |
def fromxlsx(filename, sheet=None, range_string=None, min_row=None, |
| 12 |
min_col=None, max_row=None, max_col=None, read_only=False, |
| 13 |
**kwargs): |
| 14 |
""" |
| 15 |
Extract a table from a sheet in an Excel .xlsx file. |
| 16 |
|
| 17 |
N.B., the sheet name is case sensitive. |
| 18 |
|
| 19 |
The `sheet` argument can be omitted, in which case the first sheet in |
| 20 |
the workbook is used by default. |
| 21 |
|
| 22 |
The `range_string` argument can be used to provide a range string |
| 23 |
specifying a range of cells to extract. |
| 24 |
|
| 25 |
The `min_row`, `min_col`, `max_row` and `max_col` arguments can be |
| 26 |
used to limit the range of cells to extract. They will be ignored |
| 27 |
if `range_string` is provided. |
| 28 |
|
| 29 |
The `read_only` argument determines how openpyxl returns the loaded |
| 30 |
workbook. Default is `False` as it prevents some LibreOffice files |
| 31 |
from getting truncated at 65536 rows. `True` should be faster if the |
| 32 |
file use is read-only and the files are made with Microsoft Excel. |
| 33 |
|
| 34 |
Any other keyword arguments are passed through to |
| 35 |
:func:`openpyxl.load_workbook()`. |
| 36 |
|
| 37 |
""" |
| 38 |
|
| 39 |
return XLSXView(filename, sheet=sheet, range_string=range_string, |
| 40 |
min_row=min_row, min_col=min_col, max_row=max_row, |
| 41 |
max_col=max_col, read_only=read_only, **kwargs) |
| 42 |
|
| 43 |
|
| 44 |
class XLSXView(Table): |
| 45 |
|
| 46 |
def __init__(self, filename, sheet=None, range_string=None, |
| 47 |
min_row=None, min_col=None, max_row=None, max_col=None, |
| 48 |
read_only=False, **kwargs): |
| 49 |
self.filename = filename |
| 50 |
self.sheet = sheet |
| 51 |
self.range_string = range_string |
| 52 |
self.min_row = min_row |
| 53 |
self.min_col = min_col |
| 54 |
self.max_row = max_row |
| 55 |
self.max_col = max_col |
| 56 |
self.read_only = read_only |
| 57 |
self.kwargs = kwargs |
| 58 |
|
| 59 |
def __iter__(self): |
| 60 |
import openpyxl |
| 61 |
source = read_source_from_arg(self.filename) |
| 62 |
with source.open('rb') as source2: |
| 63 |
wb = openpyxl.load_workbook(filename=source2, |
| 64 |
read_only=self.read_only, |
| 65 |
**self.kwargs) |
| 66 |
if self.sheet is None: |
| 67 |
ws = wb[wb.sheetnames[0]] |
| 68 |
elif isinstance(self.sheet, int): |
| 69 |
ws = wb[wb.sheetnames[self.sheet]] |
| 70 |
else: |
| 71 |
ws = wb[str(self.sheet)] |
| 72 |
if self.range_string is not None: |
| 73 |
rows = ws[self.range_string] |
| 74 |
else: |
| 75 |
rows = ws.iter_rows(min_row=self.min_row, |
| 76 |
min_col=self.min_col, |
| 77 |
max_row=self.max_row, |
| 78 |
max_col=self.max_col) |
| 79 |
for row in rows: |
| 80 |
yield tuple(cell.value for cell in row) |
| 81 |
try: |
| 82 |
wb._archive.close() |
| 83 |
except AttributeError: |
| 84 |
# just here in case openpyxl stops exposing an _archive property. |
| 85 |
pass |
| 86 |
|
| 87 |
|
| 88 |
def toxlsx(tbl, filename, sheet=None, write_header=True, mode="replace"): |
| 89 |
""" |
| 90 |
Write a table to a new Excel .xlsx file. |
| 91 |
|
| 92 |
N.B., the sheet name is case sensitive. |
| 93 |
|
| 94 |
The `mode` argument controls how the file and sheet are treated: |
| 95 |
|
| 96 |
- `replace`: This is the default. It either replaces or adds a |
| 97 |
named sheet, or if no sheet name is provided, all sheets |
| 98 |
(overwrites the entire file). |
| 99 |
|
| 100 |
- `overwrite`: Always overwrites the file. This produces a file |
| 101 |
with a single sheet. |
| 102 |
|
| 103 |
- `add`: Adds a new sheet. Raises `ValueError` if a named sheet |
| 104 |
already exists. |
| 105 |
|
| 106 |
The `sheet` argument can be omitted in all cases. The new sheet |
| 107 |
will then get a default name. |
| 108 |
If the file does not exist, it will be created, unless `replace` |
| 109 |
mode is used with a named sheet. In the latter case, the file |
| 110 |
must exist and be a valid .xlsx file. |
| 111 |
""" |
| 112 |
wb = _load_or_create_workbook(filename, mode, sheet) |
| 113 |
ws = _insert_sheet_on_workbook(mode, sheet, wb) |
| 114 |
if write_header: |
| 115 |
it = iter(tbl) |
| 116 |
try: |
| 117 |
hdr = next(it) |
| 118 |
flds = list(map(text_type, hdr)) |
| 119 |
rows = itertools.chain([flds], it) |
| 120 |
except StopIteration: |
| 121 |
rows = it |
| 122 |
else: |
| 123 |
rows = data(tbl) |
| 124 |
for row in rows: |
| 125 |
ws.append(row) |
| 126 |
target = write_source_from_arg(filename) |
| 127 |
with target.open('wb') as target2: |
| 128 |
wb.save(target2) |
| 129 |
|
| 130 |
|
| 131 |
def _load_or_create_workbook(filename, mode, sheet): |
| 132 |
if PY3: |
| 133 |
FileNotFound = FileNotFoundError |
| 134 |
else: |
| 135 |
FileNotFound = IOError |
| 136 |
|
| 137 |
import openpyxl |
| 138 |
wb = None |
| 139 |
if not (mode == "overwrite" or (mode == "replace" and sheet is None)): |
| 140 |
try: |
| 141 |
source = read_source_from_arg(filename) |
| 142 |
with source.open('rb') as source2: |
| 143 |
wb = openpyxl.load_workbook(filename=source2, read_only=False) |
| 144 |
except FileNotFound: |
| 145 |
wb = None |
| 146 |
if wb is None: |
| 147 |
wb = openpyxl.Workbook(write_only=True) |
| 148 |
return wb |
| 149 |
|
| 150 |
|
| 151 |
def _insert_sheet_on_workbook(mode, sheet, wb): |
| 152 |
if mode == "replace": |
| 153 |
try: |
| 154 |
ws = wb[str(sheet)] |
| 155 |
ws.delete_rows(1, ws.max_row) |
| 156 |
except KeyError: |
| 157 |
ws = wb.create_sheet(title=sheet) |
| 158 |
elif mode == "add": |
| 159 |
ws = wb.create_sheet(title=sheet) |
| 160 |
# it creates a sheet named "foo1" if "foo" exists. |
| 161 |
if sheet is not None and ws.title != sheet: |
| 162 |
raise ValueError("Sheet %s already exists in file" % sheet) |
| 163 |
elif mode == "overwrite": |
| 164 |
ws = wb.create_sheet(title=sheet) |
| 165 |
else: |
| 166 |
raise ValueError("Unknown mode '%s'" % mode) |
| 167 |
return ws |
| 168 |
|
| 169 |
|
| 170 |
Table.toxlsx = toxlsx |
| 171 |
|
| 172 |
|
| 173 |
def appendxlsx(tbl, filename, sheet=None, write_header=False): |
| 174 |
""" |
| 175 |
Appends rows to an existing Excel .xlsx file. |
| 176 |
""" |
| 177 |
|
| 178 |
import openpyxl |
| 179 |
source = read_source_from_arg(filename) |
| 180 |
with source.open('rb') as source2: |
| 181 |
wb = openpyxl.load_workbook(filename=source2, read_only=False) |
| 182 |
if sheet is None: |
| 183 |
ws = wb[wb.sheetnames[0]] |
| 184 |
elif isinstance(sheet, int): |
| 185 |
ws = wb[wb.sheetnames[sheet]] |
| 186 |
else: |
| 187 |
ws = wb[str(sheet)] |
| 188 |
if write_header: |
| 189 |
it = iter(tbl) |
| 190 |
try: |
| 191 |
hdr = next(it) |
| 192 |
flds = list(map(text_type, hdr)) |
| 193 |
rows = itertools.chain([flds], it) |
| 194 |
except StopIteration: |
| 195 |
rows = it |
| 196 |
else: |
| 197 |
rows = data(tbl) |
| 198 |
for row in rows: |
| 199 |
ws.append(row) |
| 200 |
target = write_source_from_arg(filename) |
| 201 |
with target.open('wb') as target2: |
| 202 |
wb.save(target2) |
| 203 |
|
| 204 |
|
| 205 |
Table.appendxlsx = appendxlsx |