or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

charts-visualization.mdcli.mdcollections-functions.mdconstants.mdconversion.mdcore-objects.mdindex.mdpro-features.mdudfs.mdutilities.md

core-objects.mddocs/

0

# Core Excel Objects

1

2

Primary classes for interacting with Excel applications, workbooks, worksheets, and cell ranges. These form the foundation of xlwings' object model and provide the main interface for Excel automation across all supported platforms.

3

4

## Capabilities

5

6

### App - Excel Application

7

8

Represents an Excel application instance. The App class provides control over the Excel application itself, including visibility, calculation settings, and lifecycle management.

9

10

```python { .api }

11

class App:

12

def __init__(self, visible=None, spec=None, add_book=True, xl=None):

13

"""

14

Create or connect to an Excel application.

15

16

Args:

17

visible (bool, optional): Make Excel visible. Defaults to False.

18

spec (str, optional): App specification for engine selection.

19

add_book (bool): Whether to add a new workbook. Defaults to True.

20

xl (object, optional): Existing Excel application object.

21

"""

22

23

def activate(self):

24

"""Activate the Excel application (bring to foreground)."""

25

26

def calculate(self, calculation=None):

27

"""

28

Trigger Excel calculation.

29

30

Args:

31

calculation (str, optional): Calculation type ('xlCalculationAutomatic',

32

'xlCalculationManual', 'xlCalculationSemiautomatic').

33

"""

34

35

def kill(self):

36

"""Forcefully terminate the Excel application process."""

37

38

def quit(self):

39

"""Quit the Excel application gracefully."""

40

41

@property

42

def books(self) -> Books:

43

"""Collection of all workbooks in this application."""

44

45

@property

46

def calculation(self) -> str:

47

"""Get/set calculation mode ('automatic', 'manual', 'semiautomatic')."""

48

49

@calculation.setter

50

def calculation(self, value: str): ...

51

52

@property

53

def display_alerts(self) -> bool:

54

"""Get/set whether Excel displays alerts and dialog boxes."""

55

56

@display_alerts.setter

57

def display_alerts(self, value: bool): ...

58

59

@property

60

def screen_updating(self) -> bool:

61

"""Get/set whether Excel updates the screen during operations."""

62

63

@screen_updating.setter

64

def screen_updating(self, value: bool): ...

65

66

@property

67

def visible(self) -> bool:

68

"""Get/set Excel application visibility."""

69

70

@visible.setter

71

def visible(self, value: bool): ...

72

73

@property

74

def version(self) -> VersionNumber:

75

"""Excel version number object with major, minor attributes."""

76

77

@property

78

def api(self):

79

"""Access to the native Excel application object."""

80

```

81

82

Usage example:

83

84

```python

85

import xlwings as xw

86

87

# Create new Excel application (invisible by default)

88

app = xw.App()

89

90

# Create visible Excel application

91

app = xw.App(visible=True)

92

93

# Configure application settings

94

app.display_alerts = False

95

app.screen_updating = False

96

app.calculation = 'manual'

97

98

# Access workbooks

99

wb = app.books.add()

100

101

# Clean up

102

app.quit()

103

```

104

105

### Book - Excel Workbook

106

107

Represents an Excel workbook (.xlsx, .xlsm, etc.). The Book class manages workbook-level operations including saving, closing, and accessing sheets.

108

109

```python { .api }

110

class Book:

111

def activate(self):

112

"""Activate this workbook (bring to foreground)."""

113

114

def close(self):

115

"""Close the workbook."""

116

117

def save(self, path=None):

118

"""

119

Save the workbook.

120

121

Args:

122

path (str, optional): File path. If None, saves to current location.

123

"""

124

125

def fullname(self) -> str:

126

"""Full path of the workbook file."""

127

128

def json(self):

129

"""Export workbook data as JSON."""

130

131

@property

132

def app(self) -> App:

133

"""The Excel application containing this workbook."""

134

135

@property

136

def name(self) -> str:

137

"""Workbook filename."""

138

139

@property

140

def sheets(self) -> Sheets:

141

"""Collection of all worksheets in this workbook."""

142

143

@property

144

def names(self) -> Names:

145

"""Collection of all named ranges in this workbook."""

146

147

@property

148

def selection(self) -> Range:

149

"""Currently selected range in the active sheet."""

150

151

@property

152

def api(self):

153

"""Access to the native Excel workbook object."""

154

```

155

156

Usage example:

157

158

```python

159

import xlwings as xw

160

161

# Open existing workbook

162

wb = xw.books.open('/path/to/workbook.xlsx')

163

164

# Create new workbook

165

app = xw.App()

166

wb = app.books.add()

167

168

# Work with workbook

169

wb.name # Get filename

170

wb.fullname() # Get full path

171

ws = wb.sheets[0] # Access first sheet

172

173

# Save and close

174

wb.save('/path/to/new_location.xlsx')

175

wb.close()

176

```

177

178

### Sheet - Excel Worksheet

179

180

Represents an Excel worksheet within a workbook. The Sheet class provides access to worksheet-level operations and serves as the primary interface for accessing ranges.

181

182

```python { .api }

183

class Sheet:

184

def activate(self):

185

"""Activate this worksheet (make it the active sheet)."""

186

187

def clear(self):

188

"""Clear all content and formatting from the worksheet."""

189

190

def delete(self):

191

"""Delete this worksheet from the workbook."""

192

193

def copy(self, before=None, after=None):

194

"""

195

Copy this worksheet.

196

197

Args:

198

before (Sheet, optional): Sheet to insert before.

199

after (Sheet, optional): Sheet to insert after.

200

"""

201

202

def range(self, cell1, cell2=None) -> Range:

203

"""

204

Create a Range object.

205

206

Args:

207

cell1 (str or tuple): Cell address like 'A1' or (row, col) tuple.

208

cell2 (str or tuple, optional): End cell for range.

209

210

Returns:

211

Range: Range object representing the specified cells.

212

"""

213

214

@property

215

def book(self) -> Book:

216

"""The workbook containing this worksheet."""

217

218

@property

219

def name(self) -> str:

220

"""Worksheet name."""

221

222

@name.setter

223

def name(self, value: str): ...

224

225

@property

226

def charts(self) -> Charts:

227

"""Collection of all charts in this worksheet."""

228

229

@property

230

def pictures(self) -> Pictures:

231

"""Collection of all pictures in this worksheet."""

232

233

@property

234

def shapes(self) -> Shapes:

235

"""Collection of all shapes in this worksheet."""

236

237

@property

238

def used_range(self) -> Range:

239

"""Range representing all used cells in the worksheet."""

240

241

@property

242

def api(self):

243

"""Access to the native Excel worksheet object."""

244

```

245

246

Usage example:

247

248

```python

249

import xlwings as xw

250

251

wb = xw.books.add()

252

ws = wb.sheets[0]

253

254

# Rename worksheet

255

ws.name = 'MyData'

256

257

# Access ranges

258

ws.range('A1').value = 'Hello World'

259

ws.range('A1:C3').value = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

260

261

# Get used range

262

data_range = ws.used_range

263

print(data_range.address) # e.g., '$A$1:$C$3'

264

265

# Work with charts and pictures

266

chart = ws.charts.add()

267

ws.pictures.add('/path/to/image.png')

268

```

269

270

### Range - Excel Cell Range

271

272

The most feature-rich class in xlwings, representing Excel cell ranges. Range provides comprehensive functionality for data manipulation, formatting, navigation, and conversion between Python and Excel data types.

273

274

```python { .api }

275

class Range:

276

# Data operations

277

def clear(self):

278

"""Clear both content and formatting from the range."""

279

280

def clear_contents(self):

281

"""Clear only content, preserve formatting."""

282

283

def copy(self, destination=None):

284

"""

285

Copy the range to clipboard or destination.

286

287

Args:

288

destination (Range, optional): Target range for paste operation.

289

"""

290

291

def paste(self, paste=None):

292

"""

293

Paste clipboard content to this range.

294

295

Args:

296

paste (str, optional): Paste type ('xlPasteValues', 'xlPasteFormats', etc.).

297

"""

298

299

def delete(self, shift=None):

300

"""

301

Delete the range and shift surrounding cells.

302

303

Args:

304

shift (str, optional): Shift direction ('xlShiftUp', 'xlShiftToLeft').

305

"""

306

307

def merge(self, across=False):

308

"""

309

Merge cells in the range.

310

311

Args:

312

across (bool): Merge across columns only if True.

313

"""

314

315

# Navigation and sizing

316

def end(self, direction):

317

"""

318

Navigate to end of continuous data in given direction.

319

320

Args:

321

direction (str): Direction ('up', 'down', 'left', 'right').

322

323

Returns:

324

Range: Range at the end of continuous data.

325

"""

326

327

def expand(self, mode='table'):

328

"""

329

Expand range to include surrounding data.

330

331

Args:

332

mode (str): Expansion mode ('table', 'down', 'right').

333

334

Returns:

335

Range: Expanded range.

336

"""

337

338

def offset(self, row_offset=0, column_offset=0):

339

"""

340

Create new range offset from current range.

341

342

Args:

343

row_offset (int): Rows to offset (positive = down, negative = up).

344

column_offset (int): Columns to offset (positive = right, negative = left).

345

346

Returns:

347

Range: New range at offset position.

348

"""

349

350

def resize(self, nrows=None, ncols=None):

351

"""

352

Resize the range to specified dimensions.

353

354

Args:

355

nrows (int, optional): Number of rows. None keeps current.

356

ncols (int, optional): Number of columns. None keeps current.

357

358

Returns:

359

Range: Resized range.

360

"""

361

362

# Data properties

363

@property

364

def value(self):

365

"""

366

Get/set cell values. Supports various Python data types:

367

- Single values: int, float, str, datetime, None

368

- Lists and nested lists for multi-cell ranges

369

- pandas DataFrames and Series

370

- NumPy arrays

371

"""

372

373

@value.setter

374

def value(self, data): ...

375

376

@property

377

def formula(self) -> str:

378

"""Get/set Excel formula (single cell)."""

379

380

@formula.setter

381

def formula(self, value: str): ...

382

383

@property

384

def formula_array(self) -> str:

385

"""Get/set array formula."""

386

387

@formula_array.setter

388

def formula_array(self, value: str): ...

389

390

# Range properties

391

@property

392

def address(self) -> str:

393

"""Range address in A1 notation (e.g., '$A$1:$C$3')."""

394

395

@property

396

def column(self) -> int:

397

"""First column number (1-based)."""

398

399

@property

400

def row(self) -> int:

401

"""First row number (1-based)."""

402

403

@property

404

def shape(self) -> tuple:

405

"""Range dimensions as (rows, columns) tuple."""

406

407

@property

408

def size(self) -> int:

409

"""Total number of cells in the range."""

410

411

@property

412

def width(self) -> float:

413

"""Range width in points."""

414

415

@property

416

def height(self) -> float:

417

"""Range height in points."""

418

419

@property

420

def current_region(self) -> Range:

421

"""Range representing the continuous data region around this range."""

422

423

# Formatting properties

424

@property

425

def color(self):

426

"""Get/set background color as RGB tuple or None."""

427

428

@color.setter

429

def color(self, value): ...

430

431

@property

432

def font(self):

433

"""Access to font formatting properties."""

434

435

@property

436

def number_format(self) -> str:

437

"""Get/set number format string."""

438

439

@number_format.setter

440

def number_format(self, value: str): ...

441

442

# Additional properties

443

@property

444

def note(self):

445

"""Get/set cell note/comment."""

446

447

@note.setter

448

def note(self, value): ...

449

450

@property

451

def hyperlink(self) -> str:

452

"""Get/set hyperlink URL."""

453

454

@hyperlink.setter

455

def hyperlink(self, value: str): ...

456

457

@property

458

def wrap_text(self) -> bool:

459

"""Get/set text wrapping."""

460

461

@wrap_text.setter

462

def wrap_text(self, value: bool): ...

463

464

@property

465

def columns(self) -> RangeColumns:

466

"""Column collection for this range."""

467

468

@property

469

def rows(self) -> RangeRows:

470

"""Row collection for this range."""

471

472

@property

473

def api(self):

474

"""Access to the native Excel range object."""

475

```

476

477

Usage examples:

478

479

```python

480

import xlwings as xw

481

import pandas as pd

482

import numpy as np

483

484

wb = xw.books.add()

485

ws = wb.sheets[0]

486

487

# Basic value operations

488

ws.range('A1').value = 'Hello'

489

ws.range('B1').value = 42

490

ws.range('C1').value = 3.14159

491

492

# Multi-cell operations

493

ws.range('A2:C4').value = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

494

data = ws.range('A2:C4').value

495

print(data) # Nested list

496

497

# pandas DataFrame integration

498

df = pd.DataFrame({

499

'Name': ['Alice', 'Bob', 'Charlie'],

500

'Age': [25, 30, 35],

501

'Score': [85.5, 90.2, 78.9]

502

})

503

ws.range('E1').value = df

504

505

# Read DataFrame back

506

df_range = ws.range('E1').expand()

507

df_back = df_range.options(pd.DataFrame, header=1, index=False).value

508

509

# NumPy array support

510

arr = np.random.rand(5, 3)

511

ws.range('A10').value = arr

512

513

# Range navigation

514

start_range = ws.range('A1')

515

end_range = start_range.end('down') # Navigate to last non-empty cell

516

current_region = start_range.current_region # Get continuous data region

517

518

# Range manipulation

519

ws.range('A1:C1').merge() # Merge cells

520

ws.range('A5:C5').color = (255, 255, 0) # Yellow background

521

ws.range('A6').font.bold = True

522

523

# Formulas

524

ws.range('D1').formula = '=SUM(A1:C1)'

525

ws.range('D2:D4').formula = 'A2:A4 * 2'

526

```

527

528

### Named Ranges

529

530

Represents Excel named ranges that provide meaningful names for cell references throughout the workbook.

531

532

```python { .api }

533

class Name:

534

def delete(self):

535

"""Delete this named range."""

536

537

@property

538

def name(self) -> str:

539

"""The name of the named range."""

540

541

@property

542

def refers_to(self) -> str:

543

"""Formula string that the name refers to."""

544

545

@property

546

def refers_to_range(self) -> Range:

547

"""Range object that the name refers to."""

548

549

@property

550

def api(self):

551

"""Access to the native Excel name object."""

552

```

553

554

Usage example:

555

556

```python

557

import xlwings as xw

558

559

wb = xw.books.add()

560

ws = wb.sheets[0]

561

562

# Create data and named range

563

ws.range('A1:C3').value = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

564

wb.names.add('MyData', 'Sheet1!$A$1:$C$3')

565

566

# Access named range

567

named_range = wb.names['MyData']

568

print(named_range.refers_to) # '=Sheet1!$A$1:$C$3'

569

570

# Use named range in formulas

571

ws.range('D1').formula = '=SUM(MyData)'

572

573

# Get range object from name

574

data_range = named_range.refers_to_range

575

print(data_range.value)

576

```

577

578

## Types

579

580

```python { .api }

581

# Collection types

582

Apps = Collection[App]

583

Books = Collection[Book]

584

Sheets = Collection[Sheet]

585

Charts = Collection[Chart]

586

Pictures = Collection[Picture]

587

Shapes = Collection[Shape]

588

Names = Collection[Name]

589

RangeColumns = Collection # Columns within a range

590

RangeRows = Collection # Rows within a range

591

592

# Utility types

593

class VersionNumber:

594

"""Excel version number with major/minor properties."""

595

@property

596

def major(self) -> int: ...

597

@property

598

def minor(self) -> int: ...

599

```