add write to xl
This commit is contained in:
parent
73e2bb03ea
commit
8c1258aa4f
18
xl/README.md
18
xl/README.md
@ -5,7 +5,7 @@ pip install git+{reponame}
|
||||
```
|
||||
|
||||
|
||||
example usage :
|
||||
example read :
|
||||
|
||||
|
||||
``` python
|
||||
@ -16,4 +16,20 @@ sheet_name = "Sheet"
|
||||
with XL(file_path) as excel_to_dict:
|
||||
data = excel_to_dict.sheet_to_dict(sheet_name)
|
||||
print(data)
|
||||
```
|
||||
|
||||
|
||||
example write :
|
||||
|
||||
|
||||
``` python
|
||||
from xl import XL
|
||||
|
||||
file_path = "./1.xlsx"
|
||||
data = [
|
||||
{"Name":"Alice", "Age":30},
|
||||
{"Name":"Bob", "Age":25},
|
||||
{"Name":"Charlie", "Age":35},
|
||||
]
|
||||
XL(file_path).json_to_sheet(data)
|
||||
```
|
||||
23
xl/main.py
23
xl/main.py
@ -43,4 +43,25 @@ class XL:
|
||||
if row_dict: # Only include non-empty rows
|
||||
data_list.append(row_dict)
|
||||
|
||||
return data_list
|
||||
return data_list
|
||||
|
||||
def json_to_sheet(self, data:list[dict]):
|
||||
"""
|
||||
Convert a json to a sheet.
|
||||
"""
|
||||
workbook = openpyxl.Workbook()
|
||||
sheet = workbook.active
|
||||
|
||||
headers = []
|
||||
for item in data:
|
||||
for key in item:
|
||||
if key not in headers:
|
||||
headers.append(key)
|
||||
|
||||
for col_index, header in enumerate(headers):
|
||||
sheet.cell(row=1, column=col_index+1, value=header)
|
||||
|
||||
for row_index, row_data in enumerate(data):
|
||||
for col_index, key in enumerate(headers):
|
||||
sheet.cell(row=row_index+2, column=col_index+1, value=row_data.get(key, ""))
|
||||
workbook.save(self.file_path)
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user