openpyxl 借助 smbprotocol 直接读取 smb 中excel 直接写入 共享盘

import os.path
from io import BytesIO
from openpyxl import load_workbook, Workbook

from smbclient import \
    (listdir,
     mkdir,
     open_file,
     copyfile,
     register_session,
     rmdir,
     scandir,
     makedirs,
     delete_session)
from smbclient.path import isdir, exists

server = '127.0.0.1'
username = 'username'
password = 'password'
# Optional - register the server with explicit credentials
register_session(server, username=username, password=password)

remote_directory = r'\\127.0.0.1\123'
remote_file = r"\\127.0.0.1\01_result.xlsx"
remote_save_excel = r"\\127.0.0.1\01_save_result.xlsx"

# # Create a directory (only the first request needs credentials)
# mkdir(r"\\server\share\directory", username="user", password="pass")
#
# # Remove a directory
# rmdir(r"\\server\share\directory")
#
# # Checking whether a file is a directory
# d_filename = r"\\server\share\directory"
# print("Is file {} dir?: {}".format(d_filename, isdir(d_filename)))

# List the files/directories inside a dir
# for filename in listdir(r"\\server\share\directory"):
#     print(filename)

# Use scandir as a more efficient directory listing as it already contains info like stat and attributes.
# for file_info in scandir(remote_directory):
#     file_inode = file_info.inode()
#     if file_info.is_file():
#         print("File: %s %d" % (file_info.name, file_inode))
#     elif file_info.is_dir():
#         print("Dir: %s %d" % (file_info.name, file_inode))
#     else:
#         print("Symlink: %s %d" % (file_info.name, file_inode))

exists_status = exists(remote_directory)
print('exists_status', exists_status)
makedirs(remote_directory, exist_ok=True)

with open_file(remote_file, mode='rb') as file:
    excel_data = file.read()


excel_file= excel_file2 = BytesIO(excel_data)
wb = load_workbook(excel_file, read_only=True)

# Access worksheets and cells
worksheet = wb.active
for row in worksheet.iter_rows():
    for cell in row:
        print(cell.value, end='\t')
    print()

wb = Workbook()
worksheet = wb.active
worksheet['A1'] = 'Hello'
worksheet['B1'] = 'World'

# Save Excel data to a BytesIO object
excel_file = BytesIO()
wb.save(excel_file)

# Save Excel data to a file
with open_file(remote_save_excel, mode='wb') as file:
    file.write(excel_file2.getvalue())
    print('write remote excel file success', remote_save_excel)

参考
https://github.com/jborean93/smbprotocol/blob/master/examples/high-level/file-management.py
https://github.com/jborean93/smbprotocol/tree/master/examples

你可能感兴趣的:(python,windows,excel,windows,java)