如何打印工作表索引内容?需输出sheet对象及xls文件相关效果
Hey there, sounds like you’re trying to get a meaningful printout of your sheet object that aligns with how your XLS file actually looks, instead of the generic "EDIT Output" you got from Ashinish's solution. Let’s break this down based on common libraries used for Excel handling:
Using OpenPyXL (Best for Style Preservation)
If you’re working with .xlsx files, OpenPyXL lets you dig into both cell values and styling details. Here’s a snippet that will print out the sheet’s structure and cell data alongside key styles:
from openpyxl import load_workbook # Load your Excel file wb = load_workbook("your_target_file.xlsx") sheet = wb["YourSheetName"] # Or use wb.active for the default sheet # Print basic sheet metadata first print(f"Sheet Name: {sheet.title}") print(f"Total Rows: {sheet.max_row}") print(f"Total Columns: {sheet.max_column}\n") # Iterate through each cell to print content + style info for row in sheet.iter_rows(values_only=False): row_output = [] for cell in row: # Capture key style attributes that match your XLS presentation cell_details = ( f"Value: {cell.value} | " f"Font: {cell.font.name} | " f"Size: {cell.font.size} | " f"Bold: {'Yes' if cell.font.bold else 'No'} | " f"Fill: {cell.fill.start_color.index if cell.fill.start_color.index != '00000000' else 'None'}" ) row_output.append(cell_details) print(" | ".join(row_output))
This avoids the generic object reference printout and instead shows a row-by-row breakdown that mirrors your XLS file’s content and styling.
Using Pandas (For Quick Data-Focused Printing)
If you’re more concerned with the data structure than exact styling, Pandas can give you a clean, formatted printout of the sheet’s data:
import pandas as pd # Read the sheet into a DataFrame df = pd.read_excel("your_target_file.xlsx", sheet_name="YourSheetName") # Print the DataFrame with formatted output print("Sheet Data:") print(df.to_string(index=False)) # If you need to retain basic styling for export, use Styler styled_df = df.style styled_df.to_excel("formatted_output.xlsx", engine="openpyxl")
Why You Got the "EDIT Output"
Chances are Ashinish's solution just did a raw print(sheet) which only outputs the sheet object’s internal reference (like <Worksheet "Sheet1">). To get a useful printout that matches your XLS presentation, you need to explicitly iterate through cells and extract the content/style details as shown above.
内容的提问来源于stack exchange,提问作者MikiBelavista

