mbu-msoffice-integration 1.0.4__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- mbu_msoffice_integration-1.0.4/LICENSE +21 -0
- mbu_msoffice_integration-1.0.4/PKG-INFO +20 -0
- mbu_msoffice_integration-1.0.4/README.md +1 -0
- mbu_msoffice_integration-1.0.4/mbu_msoffice_integration.egg-info/PKG-INFO +20 -0
- mbu_msoffice_integration-1.0.4/mbu_msoffice_integration.egg-info/SOURCES.txt +11 -0
- mbu_msoffice_integration-1.0.4/mbu_msoffice_integration.egg-info/dependency_links.txt +1 -0
- mbu_msoffice_integration-1.0.4/mbu_msoffice_integration.egg-info/requires.txt +6 -0
- mbu_msoffice_integration-1.0.4/mbu_msoffice_integration.egg-info/top_level.txt +1 -0
- mbu_msoffice_integration-1.0.4/msoffice/__init__.py +0 -0
- mbu_msoffice_integration-1.0.4/msoffice/excel_reader.py +228 -0
- mbu_msoffice_integration-1.0.4/msoffice/sharepoint_class.py +527 -0
- mbu_msoffice_integration-1.0.4/pyproject.toml +26 -0
- mbu_msoffice_integration-1.0.4/setup.cfg +4 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024 AAK-MBU
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: mbu_msoffice_integration
|
|
3
|
+
Version: 1.0.4
|
|
4
|
+
Summary: Repo containing functionality related to MSOffice
|
|
5
|
+
Author-email: MBU <rpa@mbu.aarhus.dk>
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Classifier: Programming Language :: Python :: 3
|
|
8
|
+
Classifier: Operating System :: Microsoft :: Windows
|
|
9
|
+
Requires-Python: >=3.7
|
|
10
|
+
Description-Content-Type: text/markdown
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Requires-Dist: cryptography>=43.0.0
|
|
13
|
+
Requires-Dist: pyodbc>=5.1.0
|
|
14
|
+
Requires-Dist: python-dateutil==2.9.*
|
|
15
|
+
Requires-Dist: openpyxl>=3.1.2
|
|
16
|
+
Requires-Dist: pandas>=2.2.3
|
|
17
|
+
Requires-Dist: office365-rest-python-client
|
|
18
|
+
Dynamic: license-file
|
|
19
|
+
|
|
20
|
+
Repo containing functionality related to MSOffice
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
Repo containing functionality related to MSOffice
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: mbu_msoffice_integration
|
|
3
|
+
Version: 1.0.4
|
|
4
|
+
Summary: Repo containing functionality related to MSOffice
|
|
5
|
+
Author-email: MBU <rpa@mbu.aarhus.dk>
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Classifier: Programming Language :: Python :: 3
|
|
8
|
+
Classifier: Operating System :: Microsoft :: Windows
|
|
9
|
+
Requires-Python: >=3.7
|
|
10
|
+
Description-Content-Type: text/markdown
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Requires-Dist: cryptography>=43.0.0
|
|
13
|
+
Requires-Dist: pyodbc>=5.1.0
|
|
14
|
+
Requires-Dist: python-dateutil==2.9.*
|
|
15
|
+
Requires-Dist: openpyxl>=3.1.2
|
|
16
|
+
Requires-Dist: pandas>=2.2.3
|
|
17
|
+
Requires-Dist: office365-rest-python-client
|
|
18
|
+
Dynamic: license-file
|
|
19
|
+
|
|
20
|
+
Repo containing functionality related to MSOffice
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
mbu_msoffice_integration.egg-info/PKG-INFO
|
|
5
|
+
mbu_msoffice_integration.egg-info/SOURCES.txt
|
|
6
|
+
mbu_msoffice_integration.egg-info/dependency_links.txt
|
|
7
|
+
mbu_msoffice_integration.egg-info/requires.txt
|
|
8
|
+
mbu_msoffice_integration.egg-info/top_level.txt
|
|
9
|
+
msoffice/__init__.py
|
|
10
|
+
msoffice/excel_reader.py
|
|
11
|
+
msoffice/sharepoint_class.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
msoffice
|
|
File without changes
|
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
"""
|
|
2
|
+
This module provides the ExcelReader class to read data from Excel files with .xlsx format.
|
|
3
|
+
|
|
4
|
+
The ExcelReader class offers methods to read specific cells, rows, and convert the row data to JSON format.
|
|
5
|
+
Additionally, it provides functionalities to count the total number of rows and nodes in the JSON data.
|
|
6
|
+
|
|
7
|
+
Classes:
|
|
8
|
+
--------
|
|
9
|
+
ExcelReader
|
|
10
|
+
|
|
11
|
+
Methods:
|
|
12
|
+
--------
|
|
13
|
+
read_cells(sheet_name: str, cell_references: List[str]) -> List[Any]:
|
|
14
|
+
Reads specific cells from a given sheet.
|
|
15
|
+
|
|
16
|
+
read_rows(sheet_name: str, start_col: str, end_col: str, start_row: int = 1, rows_to_remove: int = 0) -> List[List[Any]]:
|
|
17
|
+
Reads data from a range of rows in a given sheet, with the option to remove a specified number of rows from the end.
|
|
18
|
+
|
|
19
|
+
rows_to_json(sheet_name: str, start_col: str, end_col: str, start_row: int = 1, rows_to_remove: int = 0) -> str:
|
|
20
|
+
Converts row data to structured JSON format.
|
|
21
|
+
|
|
22
|
+
get_row_count(data: List[List[Any]]) -> int:
|
|
23
|
+
Returns the total number of rows in the provided data.
|
|
24
|
+
|
|
25
|
+
get_node_count(json_data: str) -> int:
|
|
26
|
+
Returns the total number of nodes in the provided JSON data.
|
|
27
|
+
"""
|
|
28
|
+
import json
|
|
29
|
+
from typing import List, Any
|
|
30
|
+
from openpyxl import load_workbook
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class ExcelReader:
|
|
34
|
+
"""
|
|
35
|
+
A class to read data from Excel files with .xlsx format.
|
|
36
|
+
|
|
37
|
+
Attributes:
|
|
38
|
+
-----------
|
|
39
|
+
file_path : str
|
|
40
|
+
The path to the Excel file.
|
|
41
|
+
|
|
42
|
+
Methods:
|
|
43
|
+
--------
|
|
44
|
+
read_cell(sheet_name: str, cell_reference: str) -> str:
|
|
45
|
+
Reads a specific cell from a given sheet.
|
|
46
|
+
|
|
47
|
+
read_cells(sheet_name: str, cell_references: List[str]) -> List[Any]:
|
|
48
|
+
Reads specific cells from a given sheet.
|
|
49
|
+
|
|
50
|
+
read_rows(sheet_name: str, start_col: str, end_col: str, start_row: int = 1, rows_to_remove: int = 0) -> List[List[Any]]:
|
|
51
|
+
Reads data from a range of rows in a given sheet, with the option to remove a specified number of rows from the end.
|
|
52
|
+
|
|
53
|
+
rows_to_json(sheet_name: str, start_col: str, end_col: str, start_row: int = 1, rows_to_remove: int = 0) -> str:
|
|
54
|
+
Converts row data to structured JSON format.
|
|
55
|
+
|
|
56
|
+
get_row_count(data: List[List[Any]]) -> int:
|
|
57
|
+
Returns the total number of rows in the provided data.
|
|
58
|
+
"""
|
|
59
|
+
|
|
60
|
+
def __init__(self, file_path: str):
|
|
61
|
+
"""
|
|
62
|
+
Initializes the ExcelReader with the path to the Excel file.
|
|
63
|
+
|
|
64
|
+
Parameters:
|
|
65
|
+
-----------
|
|
66
|
+
file_path : str
|
|
67
|
+
The path to the Excel file.
|
|
68
|
+
"""
|
|
69
|
+
self.file_path = file_path
|
|
70
|
+
self.workbook = load_workbook(filename=file_path)
|
|
71
|
+
|
|
72
|
+
def read_cell(self, sheet_name: str, cell_reference: str) -> str:
|
|
73
|
+
"""
|
|
74
|
+
Reads a specific cell from a given sheet.
|
|
75
|
+
|
|
76
|
+
Parameters:
|
|
77
|
+
-----------
|
|
78
|
+
sheet_name : str
|
|
79
|
+
The name of the sheet to read from.
|
|
80
|
+
cell_reference : str
|
|
81
|
+
A list of cell references to read (e.g., ['A1', 'B2']).
|
|
82
|
+
|
|
83
|
+
Returns:
|
|
84
|
+
--------
|
|
85
|
+
str
|
|
86
|
+
The value from the specified cell as a string.
|
|
87
|
+
"""
|
|
88
|
+
sheet = self.workbook[sheet_name]
|
|
89
|
+
data = sheet[cell_reference].value
|
|
90
|
+
return str(data) if data is not None else ""
|
|
91
|
+
|
|
92
|
+
def read_cells(self, sheet_name: str, cell_references: List[str]) -> List[Any]:
|
|
93
|
+
"""
|
|
94
|
+
Reads specific cells from a given sheet.
|
|
95
|
+
|
|
96
|
+
Parameters:
|
|
97
|
+
-----------
|
|
98
|
+
sheet_name : str
|
|
99
|
+
The name of the sheet to read from.
|
|
100
|
+
cell_references : List[str]
|
|
101
|
+
A list of cell references to read (e.g., ['A1', 'B2']).
|
|
102
|
+
|
|
103
|
+
Returns:
|
|
104
|
+
--------
|
|
105
|
+
List[Any]
|
|
106
|
+
A list of values from the specified cells.
|
|
107
|
+
"""
|
|
108
|
+
sheet = self.workbook[sheet_name]
|
|
109
|
+
data = [sheet[cell].value for cell in cell_references]
|
|
110
|
+
return data
|
|
111
|
+
|
|
112
|
+
def read_rows(self, sheet_name: str, start_col: str, end_col: str, start_row: int = 1, rows_to_remove: int = 0) -> List[List[Any]]:
|
|
113
|
+
"""
|
|
114
|
+
Reads data from a range of rows in a given sheet, with the option to remove a specified number of rows from the end.
|
|
115
|
+
|
|
116
|
+
Parameters:
|
|
117
|
+
-----------
|
|
118
|
+
sheet_name : str
|
|
119
|
+
The name of the sheet to read from.
|
|
120
|
+
start_col : str
|
|
121
|
+
The starting column letter.
|
|
122
|
+
end_col : str
|
|
123
|
+
The ending column letter.
|
|
124
|
+
start_row : int, optional
|
|
125
|
+
The row to start reading from (default is 1).
|
|
126
|
+
rows_to_remove : int, optional
|
|
127
|
+
The number of rows to remove from the end (default is 0).
|
|
128
|
+
|
|
129
|
+
Returns:
|
|
130
|
+
--------
|
|
131
|
+
List[List[Any]]
|
|
132
|
+
A list of lists where each inner list contains the data from one row.
|
|
133
|
+
"""
|
|
134
|
+
sheet = self.workbook[sheet_name]
|
|
135
|
+
data = []
|
|
136
|
+
for row in sheet.iter_rows(min_col=self._col_to_index(start_col),
|
|
137
|
+
max_col=self._col_to_index(end_col),
|
|
138
|
+
min_row=start_row):
|
|
139
|
+
row_data = [str(cell.value) for cell in row if cell.value is not None]
|
|
140
|
+
data.append(row_data)
|
|
141
|
+
|
|
142
|
+
if rows_to_remove > 0:
|
|
143
|
+
data = self._remove_rows_from_end(data, rows_to_remove)
|
|
144
|
+
|
|
145
|
+
return data
|
|
146
|
+
|
|
147
|
+
def rows_to_json(self, sheet_name: str, start_col: str, end_col: str, start_row: int = 1, rows_to_remove: int = 0) -> str:
|
|
148
|
+
"""
|
|
149
|
+
Converts row data to structured JSON format.
|
|
150
|
+
|
|
151
|
+
Parameters:
|
|
152
|
+
-----------
|
|
153
|
+
sheet_name : str
|
|
154
|
+
The name of the sheet to read from.
|
|
155
|
+
start_col : str
|
|
156
|
+
The starting column letter.
|
|
157
|
+
end_col : str
|
|
158
|
+
The ending column letter.
|
|
159
|
+
start_row : int, optional
|
|
160
|
+
The row to start reading from (default is 1).
|
|
161
|
+
rows_to_remove : int, optional
|
|
162
|
+
The number of rows to remove from the end (default is 0).
|
|
163
|
+
|
|
164
|
+
Returns:
|
|
165
|
+
--------
|
|
166
|
+
str
|
|
167
|
+
JSON string representing the structured row data.
|
|
168
|
+
"""
|
|
169
|
+
row_data = self.read_rows(sheet_name, start_col, end_col, start_row, rows_to_remove)
|
|
170
|
+
json_data = {"row_" + str(i + start_row): row_data[i] for i in range(len(row_data))}
|
|
171
|
+
return json.dumps(json_data, indent=4, ensure_ascii=False)
|
|
172
|
+
|
|
173
|
+
def get_row_count(self, data: List[List[Any]]) -> int:
|
|
174
|
+
"""
|
|
175
|
+
Returns the total number of rows in the provided data.
|
|
176
|
+
|
|
177
|
+
Parameters:
|
|
178
|
+
-----------
|
|
179
|
+
data : List[List[Any]]
|
|
180
|
+
The list of rows to count.
|
|
181
|
+
|
|
182
|
+
Returns:
|
|
183
|
+
--------
|
|
184
|
+
int
|
|
185
|
+
The total number of rows.
|
|
186
|
+
"""
|
|
187
|
+
return len(data)
|
|
188
|
+
|
|
189
|
+
def _col_to_index(self, col: str) -> int:
|
|
190
|
+
"""
|
|
191
|
+
Converts a column letter to a 1-based index.
|
|
192
|
+
|
|
193
|
+
Parameters:
|
|
194
|
+
-----------
|
|
195
|
+
col : str
|
|
196
|
+
The column letter (e.g., 'A', 'B', ..., 'Z', 'AA', etc.).
|
|
197
|
+
|
|
198
|
+
Returns:
|
|
199
|
+
--------
|
|
200
|
+
int
|
|
201
|
+
The 1-based index of the column.
|
|
202
|
+
"""
|
|
203
|
+
index = 0
|
|
204
|
+
for char in col:
|
|
205
|
+
index = index * 26 + (ord(char.upper()) - ord('A')) + 1
|
|
206
|
+
return index
|
|
207
|
+
|
|
208
|
+
def _remove_rows_from_end(self, data: List[List[Any]], rows_to_remove: int) -> List[List[Any]]:
|
|
209
|
+
"""
|
|
210
|
+
Removes a specified number of rows from the end of the data.
|
|
211
|
+
|
|
212
|
+
Parameters:
|
|
213
|
+
-----------
|
|
214
|
+
data : List[List[Any]]
|
|
215
|
+
The list of rows to process.
|
|
216
|
+
rows_to_remove : int
|
|
217
|
+
The number of rows to remove from the end.
|
|
218
|
+
|
|
219
|
+
Returns:
|
|
220
|
+
--------
|
|
221
|
+
List[List[Any]]
|
|
222
|
+
The modified list of rows with the specified number of rows removed from the end.
|
|
223
|
+
"""
|
|
224
|
+
non_empty_row_index = len(data)
|
|
225
|
+
while non_empty_row_index > 0 and not any(data[non_empty_row_index - 1]):
|
|
226
|
+
non_empty_row_index -= 1
|
|
227
|
+
|
|
228
|
+
return data[:non_empty_row_index - rows_to_remove] if rows_to_remove > 0 else data
|
|
@@ -0,0 +1,527 @@
|
|
|
1
|
+
"""
|
|
2
|
+
This module defines a Sharepoint class that facilitates interactions with a SharePoint site.
|
|
3
|
+
It provides methods for authenticating with the site, listing files in a specified document
|
|
4
|
+
library folder, downloading files, and saving them to a local directory. The class is designed
|
|
5
|
+
to encapsulate all necessary functionalities for handling files on a SharePoint site, making it
|
|
6
|
+
suitable for scripts or applications that require automated access to SharePoint resources.
|
|
7
|
+
|
|
8
|
+
The Sharepoint class uses the SharePlum library to communicate with SharePoint, handling common
|
|
9
|
+
tasks such as authentication, file retrieval, and file management. This includes methods to
|
|
10
|
+
authenticate users, fetch file lists from specific library folders, download individual files,
|
|
11
|
+
and save them locally. The class is initialized with user credentials and site details, which
|
|
12
|
+
are used throughout the class to manage SharePoint interactions.
|
|
13
|
+
|
|
14
|
+
Usage:
|
|
15
|
+
After creating an instance of the Sharepoint class with the necessary credentials and site details,
|
|
16
|
+
users can call methods to list files in a folder, download a specific file, or retrieve and save
|
|
17
|
+
all files from a folder to a local directory. This makes it easy to integrate SharePoint file
|
|
18
|
+
management into automated workflows or systems.
|
|
19
|
+
|
|
20
|
+
Example:
|
|
21
|
+
sharepoint_details = {
|
|
22
|
+
"username": "john@do.e",
|
|
23
|
+
"password": "johndoe",
|
|
24
|
+
"site_url": "https://site_url",
|
|
25
|
+
"site_name": "department123",
|
|
26
|
+
"document_library": "Shared documents"
|
|
27
|
+
}
|
|
28
|
+
sp = Sharepoint(**sharepoint_details)
|
|
29
|
+
sp.download_files("FolderName", "C:\\LocalPath")
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
import os
|
|
33
|
+
|
|
34
|
+
import math
|
|
35
|
+
|
|
36
|
+
import traceback
|
|
37
|
+
|
|
38
|
+
from pathlib import PurePath
|
|
39
|
+
|
|
40
|
+
from io import BytesIO
|
|
41
|
+
|
|
42
|
+
from typing import Optional, List, Dict, Any, Union
|
|
43
|
+
|
|
44
|
+
from openpyxl.styles import Font, Alignment
|
|
45
|
+
from openpyxl import load_workbook
|
|
46
|
+
|
|
47
|
+
import pandas as pd
|
|
48
|
+
|
|
49
|
+
from office365.runtime.auth.user_credential import UserCredential
|
|
50
|
+
from office365.sharepoint.client_context import ClientContext
|
|
51
|
+
from office365.sharepoint.files.file import File
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class Sharepoint:
|
|
55
|
+
"""
|
|
56
|
+
A class to interact with a SharePoint site, enabling authentication, file listing,
|
|
57
|
+
downloading, uploading, and saving functionalities within a specified SharePoint document library.
|
|
58
|
+
|
|
59
|
+
Attributes:
|
|
60
|
+
username (str): Username for authentication.
|
|
61
|
+
password (str): Password for authentication.
|
|
62
|
+
site_url (str): URL of the SharePoint site.
|
|
63
|
+
site_name (str): Name of the SharePoint site.
|
|
64
|
+
document_library (str): Document library path.
|
|
65
|
+
"""
|
|
66
|
+
|
|
67
|
+
def __init__(
|
|
68
|
+
self, username: str, password: str, site_url: str, site_name: str, document_library: str
|
|
69
|
+
):
|
|
70
|
+
"""Initializes the Sharepoint class with credentials and site details."""
|
|
71
|
+
self.username = username
|
|
72
|
+
self.password = password
|
|
73
|
+
self.site_url = site_url
|
|
74
|
+
self.site_name = site_name
|
|
75
|
+
self.document_library = document_library
|
|
76
|
+
self.ctx = self._auth()
|
|
77
|
+
|
|
78
|
+
def _auth(self) -> Optional[ClientContext]:
|
|
79
|
+
"""
|
|
80
|
+
Authenticates to the SharePoint site and returns the client context.
|
|
81
|
+
|
|
82
|
+
Returns:
|
|
83
|
+
Optional[ClientContext]: A ClientContext object for interacting with the SharePoint site if authentication is successful,
|
|
84
|
+
otherwise None.
|
|
85
|
+
"""
|
|
86
|
+
try:
|
|
87
|
+
site_full_url = f"{self.site_url}/teams/{self.site_name}"
|
|
88
|
+
ctx = ClientContext(site_full_url).with_credentials(
|
|
89
|
+
UserCredential(self.username, self.password)
|
|
90
|
+
)
|
|
91
|
+
return ctx
|
|
92
|
+
except Exception as e:
|
|
93
|
+
print(f"Failed to authenticate: {e}")
|
|
94
|
+
return None
|
|
95
|
+
|
|
96
|
+
def fetch_files_list(self, folder_name: str) -> Optional[List[dict]]:
|
|
97
|
+
"""
|
|
98
|
+
Retrieves a list of files from a specified folder within the document library.
|
|
99
|
+
|
|
100
|
+
Args:
|
|
101
|
+
folder_name (str): The name of the folder within the document library.
|
|
102
|
+
|
|
103
|
+
Returns:
|
|
104
|
+
list: A list of file dictionaries in the specified folder, or None if an error occurs or if the site is not authenticated.
|
|
105
|
+
"""
|
|
106
|
+
if self.ctx:
|
|
107
|
+
try:
|
|
108
|
+
folder_url = f"/teams/{self.site_name}/{self.document_library}/{folder_name}"
|
|
109
|
+
folder = self.ctx.web.get_folder_by_server_relative_url(folder_url)
|
|
110
|
+
files = folder.files
|
|
111
|
+
self.ctx.load(files)
|
|
112
|
+
self.ctx.execute_query()
|
|
113
|
+
files_list = [{"Name": file.name} for file in files]
|
|
114
|
+
return files_list
|
|
115
|
+
except Exception as e:
|
|
116
|
+
print(f"Error retrieving files: {e}")
|
|
117
|
+
return None
|
|
118
|
+
return None
|
|
119
|
+
|
|
120
|
+
def fetch_file_content(self, file_name: str, folder_name: str) -> Optional[bytes]:
|
|
121
|
+
"""
|
|
122
|
+
Downloads a file from a specified folder within the document library.
|
|
123
|
+
|
|
124
|
+
Args:
|
|
125
|
+
file_name (str): The name of the file to be downloaded.
|
|
126
|
+
folder_name (str): The name of the folder where the file is located.
|
|
127
|
+
|
|
128
|
+
Returns:
|
|
129
|
+
Optional[bytes]: The binary content of the file if successful, otherwise None.
|
|
130
|
+
"""
|
|
131
|
+
if self.ctx:
|
|
132
|
+
try:
|
|
133
|
+
file_url = f"/teams/{self.site_name}/{self.document_library}/{folder_name}/{file_name}"
|
|
134
|
+
file = self.ctx.web.get_file_by_server_relative_url(file_url)
|
|
135
|
+
file_content = file.read().execute_query()
|
|
136
|
+
return file_content.value
|
|
137
|
+
except Exception as e:
|
|
138
|
+
print(f"Failed to download file: {e}")
|
|
139
|
+
return None
|
|
140
|
+
return None
|
|
141
|
+
|
|
142
|
+
def fetch_file_using_open_binary(self, file_name: str, folder_name: str) -> Optional[bytes]:
|
|
143
|
+
"""
|
|
144
|
+
Downloads a file using the open_binary method from SharePoint.
|
|
145
|
+
"""
|
|
146
|
+
if self.ctx:
|
|
147
|
+
try:
|
|
148
|
+
file_url = f"/teams/{self.site_name}/{self.document_library}/{folder_name}/{file_name}"
|
|
149
|
+
file_content = File.open_binary(self.ctx, file_url)
|
|
150
|
+
return file_content.content
|
|
151
|
+
except Exception:
|
|
152
|
+
print("Failed to download file:")
|
|
153
|
+
traceback.print_exc()
|
|
154
|
+
return None
|
|
155
|
+
return None
|
|
156
|
+
|
|
157
|
+
def _write_file(self, folder_destination: str, file_name: str, file_content: bytes):
|
|
158
|
+
"""
|
|
159
|
+
Saves the binary content of a file to a specified local destination.
|
|
160
|
+
|
|
161
|
+
Args:
|
|
162
|
+
folder_destination (str): The local folder path where the file will be saved.
|
|
163
|
+
file_name (str): The name of the file to be saved.
|
|
164
|
+
file_content (bytes): The binary content of the file.
|
|
165
|
+
"""
|
|
166
|
+
file_directory_path = PurePath(folder_destination, file_name)
|
|
167
|
+
with open(file_directory_path, "wb") as file:
|
|
168
|
+
file.write(file_content)
|
|
169
|
+
|
|
170
|
+
def download_file(self, folder: str, filename: str, folder_destination: str):
|
|
171
|
+
"""
|
|
172
|
+
Downloads a specified file from a specified folder and saves it to a local destination.
|
|
173
|
+
|
|
174
|
+
Args:
|
|
175
|
+
folder (str): The name of the folder in the document library containing the file.
|
|
176
|
+
filename (str): The name of the file to download.
|
|
177
|
+
folder_destination (str): The local folder path where the downloaded file will be saved.
|
|
178
|
+
"""
|
|
179
|
+
file_content = self.fetch_file_content(filename, folder)
|
|
180
|
+
if file_content:
|
|
181
|
+
self._write_file(folder_destination, filename, file_content)
|
|
182
|
+
else:
|
|
183
|
+
print(f"Failed to download {filename}")
|
|
184
|
+
|
|
185
|
+
def download_files(self, folder: str, folder_destination: str):
|
|
186
|
+
"""
|
|
187
|
+
Downloads all files from a specified folder and saves them to a local destination.
|
|
188
|
+
|
|
189
|
+
Args:
|
|
190
|
+
folder (str): The name of the folder in the document library containing the files.
|
|
191
|
+
folder_destination (str): The local folder path where the downloaded files will be saved.
|
|
192
|
+
"""
|
|
193
|
+
files_list = self.fetch_files_list(folder)
|
|
194
|
+
if files_list:
|
|
195
|
+
for file in files_list:
|
|
196
|
+
file_content = self.fetch_file_content(file["Name"], folder)
|
|
197
|
+
if file_content:
|
|
198
|
+
self._write_file(folder_destination, file["Name"], file_content)
|
|
199
|
+
else:
|
|
200
|
+
print(f"Failed to download {file['Name']}")
|
|
201
|
+
else:
|
|
202
|
+
print(f"No files found in folder {folder}")
|
|
203
|
+
|
|
204
|
+
def upload_file(self, folder_name: str, file_path: str, file_name: Optional[str] = None):
|
|
205
|
+
"""
|
|
206
|
+
Uploads a single file to a specified folder within the document library.
|
|
207
|
+
|
|
208
|
+
Args:
|
|
209
|
+
folder_name (str): The name of the folder within the document library.
|
|
210
|
+
file_path (str): The local path to the file to be uploaded.
|
|
211
|
+
file_name (Optional[str]): The name to give the file in SharePoint. If not provided, uses the name from file_path.
|
|
212
|
+
"""
|
|
213
|
+
if self.ctx:
|
|
214
|
+
try:
|
|
215
|
+
if file_name is None:
|
|
216
|
+
file_name = os.path.basename(file_path)
|
|
217
|
+
|
|
218
|
+
folder_url = f"/teams/{self.site_name}/{self.document_library}/{folder_name}"
|
|
219
|
+
target_folder = self.ctx.web.get_folder_by_server_relative_url(folder_url)
|
|
220
|
+
|
|
221
|
+
with open(file_path, 'rb') as content_file:
|
|
222
|
+
file_content = content_file.read()
|
|
223
|
+
|
|
224
|
+
target_folder.upload_file(file_name, file_content).execute_query()
|
|
225
|
+
print(f"File '{file_name}' uploaded successfully to '{folder_url}'.")
|
|
226
|
+
except Exception as e:
|
|
227
|
+
print(f"Failed to upload file '{file_name}': {e}")
|
|
228
|
+
|
|
229
|
+
def upload_files(self, folder_name: str, files: List[str]):
|
|
230
|
+
"""
|
|
231
|
+
Uploads multiple files to a specified folder within the document library.
|
|
232
|
+
|
|
233
|
+
Args:
|
|
234
|
+
folder_name (str): The name of the folder within the document library.
|
|
235
|
+
files (List[str]): A list of local file paths to be uploaded.
|
|
236
|
+
"""
|
|
237
|
+
if self.ctx:
|
|
238
|
+
for file_path in files:
|
|
239
|
+
try:
|
|
240
|
+
file_name = os.path.basename(file_path)
|
|
241
|
+
self.upload_file(folder_name, file_path, file_name)
|
|
242
|
+
except Exception as e:
|
|
243
|
+
print(f"Failed to upload file '{file_path}': {e}")
|
|
244
|
+
|
|
245
|
+
def upload_file_from_bytes(self, binary_content: bytes, file_name: str, folder_name: str):
|
|
246
|
+
"""
|
|
247
|
+
Uploads a file to SharePoint directly from a bytes object.
|
|
248
|
+
|
|
249
|
+
Args:
|
|
250
|
+
binary_content (bytes): The binary content of the file.
|
|
251
|
+
file_name (str): The name to give the file in SharePoint.
|
|
252
|
+
folder_name (str): The folder in the document library where the file will be uploaded.
|
|
253
|
+
"""
|
|
254
|
+
|
|
255
|
+
if self.ctx:
|
|
256
|
+
try:
|
|
257
|
+
folder_url = f"/teams/{self.site_name}/{self.document_library}/{folder_name}"
|
|
258
|
+
target_folder = self.ctx.web.get_folder_by_server_relative_url(folder_url)
|
|
259
|
+
|
|
260
|
+
target_folder.upload_file(file_name, binary_content).execute_query()
|
|
261
|
+
print(f"File '{file_name}' uploaded successfully to '{folder_url}'.")
|
|
262
|
+
except Exception as e:
|
|
263
|
+
print(f"Failed to upload file '{file_name}': {e}")
|
|
264
|
+
|
|
265
|
+
def append_row_to_sharepoint_excel(
|
|
266
|
+
self,
|
|
267
|
+
required_headers: Optional[List[str]] = None,
|
|
268
|
+
folder_name: str = "",
|
|
269
|
+
excel_file_name: str = "",
|
|
270
|
+
sheet_name: str = "",
|
|
271
|
+
new_rows: Union[Dict, List[Dict]] = None,
|
|
272
|
+
) -> None:
|
|
273
|
+
"""
|
|
274
|
+
• Appends one or more rows to an existing Excel file.
|
|
275
|
+
• Sorts and formats based on provided parameters.
|
|
276
|
+
"""
|
|
277
|
+
|
|
278
|
+
# Ensure new_rows is a list of dicts
|
|
279
|
+
if isinstance(new_rows, dict):
|
|
280
|
+
new_rows = [new_rows]
|
|
281
|
+
|
|
282
|
+
elif not isinstance(new_rows, list) or not all(isinstance(r, dict) for r in new_rows):
|
|
283
|
+
raise TypeError("new_rows must be a dict or a list of dicts.")
|
|
284
|
+
|
|
285
|
+
# 1. Pull file
|
|
286
|
+
binary_file = self.fetch_file_using_open_binary(excel_file_name, folder_name)
|
|
287
|
+
if binary_file is None:
|
|
288
|
+
raise FileNotFoundError(f"File '{excel_file_name}' not found in folder '{folder_name}'.")
|
|
289
|
+
|
|
290
|
+
wb = load_workbook(BytesIO(binary_file))
|
|
291
|
+
|
|
292
|
+
if sheet_name not in wb.sheetnames:
|
|
293
|
+
raise ValueError(f"Sheet '{sheet_name}' not found in '{excel_file_name}'")
|
|
294
|
+
|
|
295
|
+
ws = wb[sheet_name]
|
|
296
|
+
|
|
297
|
+
# 2. Validate headers
|
|
298
|
+
if required_headers:
|
|
299
|
+
current_headers = [cell.value for cell in ws[1]]
|
|
300
|
+
|
|
301
|
+
if current_headers != required_headers:
|
|
302
|
+
raise ValueError(
|
|
303
|
+
f"Header mismatch in sheet '{sheet_name}'!\n"
|
|
304
|
+
f"Expected: {required_headers}\n"
|
|
305
|
+
f"Found: {current_headers}"
|
|
306
|
+
)
|
|
307
|
+
|
|
308
|
+
# 2.5 Clean up empty rows before appending
|
|
309
|
+
for row_idx in range(ws.max_row, 1, -1): # Start from bottom, skip header
|
|
310
|
+
row_values = [cell.value for cell in ws[row_idx]]
|
|
311
|
+
|
|
312
|
+
if all(cell is None for cell in row_values):
|
|
313
|
+
ws.delete_rows(row_idx)
|
|
314
|
+
|
|
315
|
+
# 3. Append each new row
|
|
316
|
+
headers = [header.value for header in ws[1]]
|
|
317
|
+
|
|
318
|
+
for row_dict in new_rows:
|
|
319
|
+
ws.append([row_dict.get(header, "") for header in headers])
|
|
320
|
+
|
|
321
|
+
# 4. Save and upload
|
|
322
|
+
temp_stream = BytesIO()
|
|
323
|
+
|
|
324
|
+
wb.save(temp_stream)
|
|
325
|
+
|
|
326
|
+
temp_stream.seek(0)
|
|
327
|
+
|
|
328
|
+
self.upload_file_from_bytes(temp_stream.getvalue(), excel_file_name, folder_name)
|
|
329
|
+
|
|
330
|
+
def format_and_sort_excel_file(
|
|
331
|
+
self,
|
|
332
|
+
folder_name: str,
|
|
333
|
+
excel_file_name: str,
|
|
334
|
+
sheet_name: str,
|
|
335
|
+
sorting_keys: Optional[List[Dict[str, Any]]] = None,
|
|
336
|
+
font_config: Optional[Dict[int, Dict[str, Any]]] = None,
|
|
337
|
+
bold_rows: Optional[List[int]] = None,
|
|
338
|
+
italic_rows: Optional[List[int]] = None,
|
|
339
|
+
align_horizontal: str = "center",
|
|
340
|
+
align_vertical: str = "center",
|
|
341
|
+
column_widths: Any = "auto",
|
|
342
|
+
freeze_panes: Optional[str] = None,
|
|
343
|
+
):
|
|
344
|
+
"""
|
|
345
|
+
Sorts and formats an Excel worksheet based on provided styling and sorting rules.
|
|
346
|
+
|
|
347
|
+
Params:
|
|
348
|
+
folder_name: Name of the folder where the file resides
|
|
349
|
+
excel_file_name: Name of the excel file
|
|
350
|
+
sheet_name: Name of the sheet that will be sorted
|
|
351
|
+
sorting_keys: List of dicts like [{"key": "A", "ascending": True, "type": "datetime"}]
|
|
352
|
+
bold_rows: List of row numbers to bold (defaults to [1])
|
|
353
|
+
italic_rows: List of row numbers to italicize
|
|
354
|
+
font_config: Dict of row -> font config (overrides bold/italic)
|
|
355
|
+
align_horizontal: Horizontal text alignment
|
|
356
|
+
align_vertical: Vertical text alignment
|
|
357
|
+
column_widths: "auto" or an int to represent a pixel value
|
|
358
|
+
freeze_panes: E.g., "A2" to freeze header row
|
|
359
|
+
|
|
360
|
+
Returns:
|
|
361
|
+
Modified worksheet
|
|
362
|
+
"""
|
|
363
|
+
|
|
364
|
+
# Step 1 - Fetch the file to update from SharePoint and load it as a workbook
|
|
365
|
+
# This ensures we don't override any other sheets in the excel file
|
|
366
|
+
binary_file = self.fetch_file_using_open_binary(excel_file_name, folder_name)
|
|
367
|
+
if binary_file is None:
|
|
368
|
+
raise FileNotFoundError(f"File '{excel_file_name}' not found in folder '{folder_name}'.")
|
|
369
|
+
|
|
370
|
+
wb = load_workbook(BytesIO(binary_file))
|
|
371
|
+
if sheet_name not in wb.sheetnames:
|
|
372
|
+
raise ValueError(f"Sheet '{sheet_name}' not found in '{excel_file_name}'")
|
|
373
|
+
|
|
374
|
+
ws = wb[sheet_name]
|
|
375
|
+
|
|
376
|
+
# Step 2 - Read data into DataFrame
|
|
377
|
+
rows = list(ws.iter_rows(values_only=True))
|
|
378
|
+
header, *data_rows = rows
|
|
379
|
+
df = pd.DataFrame(data_rows, columns=header)
|
|
380
|
+
|
|
381
|
+
# Step 3 – Prepare sorting logic
|
|
382
|
+
# For each sorting instruction, we:
|
|
383
|
+
# - Extract the column to sort by (using letter, index, or name)
|
|
384
|
+
# - Convert the column values to the desired data type if specified (str, int, float, datetime)
|
|
385
|
+
# - Track which columns to sort and in which order (ascending or descending)
|
|
386
|
+
#
|
|
387
|
+
# This ensures the DataFrame is sorted correctly, even when types like dates or numbers need conversion.
|
|
388
|
+
if sorting_keys:
|
|
389
|
+
sort_columns = []
|
|
390
|
+
ascending_flags = []
|
|
391
|
+
|
|
392
|
+
for item in sorting_keys:
|
|
393
|
+
key = item.get("key")
|
|
394
|
+
ascending = item.get("ascending", True)
|
|
395
|
+
dtype = item.get("type")
|
|
396
|
+
|
|
397
|
+
if isinstance(key, int):
|
|
398
|
+
col_name = header[key]
|
|
399
|
+
|
|
400
|
+
elif isinstance(key, str) and key.isalpha():
|
|
401
|
+
col_name = header[ord(key.upper()) - ord("A")]
|
|
402
|
+
|
|
403
|
+
else:
|
|
404
|
+
col_name = key
|
|
405
|
+
|
|
406
|
+
sort_columns.append(col_name)
|
|
407
|
+
ascending_flags.append(ascending)
|
|
408
|
+
|
|
409
|
+
if dtype == "datetime":
|
|
410
|
+
df[col_name] = pd.to_datetime(df[col_name], dayfirst=True, errors="coerce")
|
|
411
|
+
|
|
412
|
+
elif dtype == "int":
|
|
413
|
+
df[col_name] = pd.to_numeric(df[col_name], errors="coerce", downcast="integer")
|
|
414
|
+
|
|
415
|
+
elif dtype == "float":
|
|
416
|
+
df[col_name] = pd.to_numeric(df[col_name], errors="coerce", downcast="float")
|
|
417
|
+
|
|
418
|
+
elif dtype == "str":
|
|
419
|
+
df[col_name] = df[col_name].astype(str)
|
|
420
|
+
|
|
421
|
+
# Step 4 – Sort
|
|
422
|
+
df.sort_values(by=sort_columns, ascending=ascending_flags, inplace=True)
|
|
423
|
+
|
|
424
|
+
# Step 5 - Overwrite worksheet
|
|
425
|
+
ws.delete_rows(1, ws.max_row)
|
|
426
|
+
|
|
427
|
+
ws.append(header)
|
|
428
|
+
|
|
429
|
+
for _, row in df.iterrows():
|
|
430
|
+
ws.append(list(row))
|
|
431
|
+
|
|
432
|
+
# Step 6 – Adjust column widths and apply wrapping if needed
|
|
433
|
+
#
|
|
434
|
+
# If column_widths is "auto":
|
|
435
|
+
# - Calculate the max content length in each column and set the column width accordingly (+2 for padding)
|
|
436
|
+
#
|
|
437
|
+
# If column_widths is a single int:
|
|
438
|
+
# - Use it as a global max width across all columns
|
|
439
|
+
# - If content fits, set width based on actual content length
|
|
440
|
+
# - If content exceeds the max width clamp column width and enable wrap_text for that column's cells
|
|
441
|
+
#
|
|
442
|
+
# Then, for wrapped cells, auto-adjust the row height:
|
|
443
|
+
# - Estimate how many lines the wrapped text would occupy and set row height accordingly to ensure all content is visible
|
|
444
|
+
if column_widths in (None, "auto"):
|
|
445
|
+
for col in ws.columns:
|
|
446
|
+
max_len = max(len(str(cell.value or "")) for cell in col)
|
|
447
|
+
|
|
448
|
+
ws.column_dimensions[col[0].column_letter].width = max_len + 2
|
|
449
|
+
|
|
450
|
+
elif isinstance(column_widths, int):
|
|
451
|
+
for col in ws.columns:
|
|
452
|
+
col_letter = col[0].column_letter
|
|
453
|
+
|
|
454
|
+
max_len = max(len(str(cell.value or "")) for cell in col)
|
|
455
|
+
|
|
456
|
+
# If content fits, auto-size
|
|
457
|
+
if max_len + 2 <= column_widths:
|
|
458
|
+
ws.column_dimensions[col_letter].width = max_len + 2
|
|
459
|
+
|
|
460
|
+
# Else, cap width and enable wrap
|
|
461
|
+
else:
|
|
462
|
+
ws.column_dimensions[col_letter].width = column_widths
|
|
463
|
+
|
|
464
|
+
for cell in col:
|
|
465
|
+
cell.alignment = Alignment(wrap_text=True)
|
|
466
|
+
|
|
467
|
+
# Here we handle row height
|
|
468
|
+
for row in ws.iter_rows():
|
|
469
|
+
max_line_count = 1
|
|
470
|
+
|
|
471
|
+
for cell in row:
|
|
472
|
+
if cell.value and cell.alignment and cell.alignment.wrap_text:
|
|
473
|
+
col_letter = cell.column_letter
|
|
474
|
+
col_width = ws.column_dimensions[col_letter].width or 10
|
|
475
|
+
chars_per_line = col_width * 1.2
|
|
476
|
+
lines = str(cell.value).split("\n")
|
|
477
|
+
line_count = sum(math.ceil(len(line) / chars_per_line) for line in lines)
|
|
478
|
+
max_line_count = max(max_line_count, line_count)
|
|
479
|
+
|
|
480
|
+
ws.row_dimensions[row[0].row].height = max_line_count * 20
|
|
481
|
+
|
|
482
|
+
else:
|
|
483
|
+
raise ValueError(f"Column width provided with incorrect datatype - datatype int expected, instead column width is of datatype {type(column_widths)}")
|
|
484
|
+
|
|
485
|
+
# Step 7 - Freeze panes if needed
|
|
486
|
+
if freeze_panes:
|
|
487
|
+
ws.freeze_panes = freeze_panes
|
|
488
|
+
|
|
489
|
+
# Step 8 – Apply base formatting
|
|
490
|
+
# For each cell in the worksheet:
|
|
491
|
+
# - Apply font styling based on either a custom `font_config` (row-specific) or default to bold/italic based on row number (e.g., header rows)
|
|
492
|
+
# - Set horizontal and vertical alignment for consistent layout
|
|
493
|
+
# - Disable text wrapping by default (wrapping will be handled later if needed)
|
|
494
|
+
#
|
|
495
|
+
# This ensures a clean, uniform look across the sheet while allowing for custom styling where defined.
|
|
496
|
+
for row_idx, row in enumerate(ws.iter_rows(), start=1):
|
|
497
|
+
for cell in row:
|
|
498
|
+
if font_config and row_idx in font_config:
|
|
499
|
+
config = font_config[row_idx]
|
|
500
|
+
|
|
501
|
+
cell.font = Font(
|
|
502
|
+
name=config.get("name", "Calibri"),
|
|
503
|
+
size=config.get("size", 11),
|
|
504
|
+
bold=config.get("bold", False),
|
|
505
|
+
italic=config.get("italic", False),
|
|
506
|
+
)
|
|
507
|
+
|
|
508
|
+
else:
|
|
509
|
+
cell.font = Font(
|
|
510
|
+
bold=row_idx in bold_rows if bold_rows else False,
|
|
511
|
+
italic=row_idx in italic_rows if italic_rows else False,
|
|
512
|
+
)
|
|
513
|
+
|
|
514
|
+
cell.alignment = Alignment(
|
|
515
|
+
horizontal=align_horizontal,
|
|
516
|
+
vertical=align_vertical,
|
|
517
|
+
wrap_text=cell.alignment.wrap_text
|
|
518
|
+
)
|
|
519
|
+
|
|
520
|
+
# Step 9 - Save and re-upload
|
|
521
|
+
temp_stream = BytesIO()
|
|
522
|
+
|
|
523
|
+
wb.save(temp_stream)
|
|
524
|
+
|
|
525
|
+
temp_stream.seek(0)
|
|
526
|
+
|
|
527
|
+
self.upload_file_from_bytes(temp_stream.getvalue(), excel_file_name, folder_name)
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=65.0"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "mbu_msoffice_integration" # 👈 must match the PyPI project name
|
|
7
|
+
version = "1.0.4"
|
|
8
|
+
authors = [
|
|
9
|
+
{ name="MBU", email="rpa@mbu.aarhus.dk" },
|
|
10
|
+
]
|
|
11
|
+
description = "Repo containing functionality related to MSOffice"
|
|
12
|
+
readme = "README.md"
|
|
13
|
+
requires-python = ">=3.7"
|
|
14
|
+
classifiers = [
|
|
15
|
+
"Programming Language :: Python :: 3",
|
|
16
|
+
"Operating System :: Microsoft :: Windows",
|
|
17
|
+
]
|
|
18
|
+
license = "MIT"
|
|
19
|
+
dependencies = [
|
|
20
|
+
"cryptography >= 43.0.0",
|
|
21
|
+
"pyodbc >= 5.1.0",
|
|
22
|
+
"python-dateutil == 2.9.*",
|
|
23
|
+
"openpyxl >= 3.1.2",
|
|
24
|
+
"pandas >= 2.2.3",
|
|
25
|
+
"office365-rest-python-client",
|
|
26
|
+
]
|