- src/dist 산출물 분리 원칙 정리(.gitignore, .gitattributes) - 루트 및 주요 폴더(config/scripts/prompts/tests/src, 런타임 폴더 5종)에 안내용 README.md 추가 - CHANGELOG.md, LICENSE, docs/ops/05-release-and-versioning.md 추가 - docs/README.md 문서 지도 갱신
3048 lines
No EOL
147 KiB
Markdown
3048 lines
No EOL
147 KiB
Markdown
# RAW RESEARCH DUMP — agent-aae3a9663f8136c70
|
||
|
||
## ORIGINAL TASK PROMPT
|
||
|
||
오늘 날짜는 2026-09-02 이다. 너는 리서치 에이전트다. 반드시 먼저 ToolSearch 로 "select:WebSearch,WebFetch" 를 로드하고, WebSearch 로 최소 8회 이상 다양한 한국어/영어 질의를 던지고, 핵심 출처 페이지는 WebFetch 로 실제 열어 내용을 확인하라. 실제로 열어 확인한 항목만 verified_by_fetch=true 로 표시하라. 존재를 확인하지 못한 URL, GitHub 저장소, 논문, CLI 플래그는 절대 지어내지 말고 confidence='low' 로 표시하거나 제외하라. 한국 사이트(nedrug.mfds.go.kr, data.go.kr 등)는 WebFetch 가 실패할 수 있으니 실패하면 그 사실을 open_questions 에 적어라. 결과의 summary/detail/recommendations 는 한국어로 쓰되 고유명사·코드·플래그는 원문 유지. 코드 스니펫은 실제 동작 가능한 수준으로 구체적으로 작성하라. 최종 출력은 StructuredOutput 스키마에 맞춰라.
|
||
|
||
프로젝트 맥락: Windows 11 PC 에서 매일 06:00 에 한국 식약처 원료의약품 등록(DMF) 공고/현황을 크롤링하여 신규/변경/취하 건을 탐지하고, 탭(시트)별로 연동된 보기 좋은 xlsx 리포트를 생성한다. 크롤링·요약 일부를 AI 에이전트 CLI(Claude Code 의 'claude -p' headless 모드 등)로 non-interactive 하게 돌리고, 재부팅 후에도 자동 복구되는 서비스/스케줄러로 운영하며, 서비스가 죽으면 Windows 알림으로 복구 안내를 띄운다.
|
||
|
||
[축 6: xlsx 탭(시트)별 연동 방법과 예쁘게 나오는 포맷팅 방법론]
|
||
조사 항목 (Python 기준, openpyxl / xlsxwriter / pandas ExcelWriter 공식 문서를 WebFetch 로 확인):
|
||
1) 시트 간 연동: 목차(INDEX) 시트에서 각 탭으로 가는 HYPERLINK("#'시트명'!A1") 및 openpyxl cell.hyperlink 내부 링크, 각 탭에서 목차로 돌아가는 링크, 정의된 이름(Defined Names), 시트 간 수식(COUNTIFS/SUMIFS/INDEX-MATCH/XLOOKUP, FILTER/UNIQUE 동적 배열을 openpyxl 로 쓸 때 _xlfn 접두어·ArrayFormula 처리), Excel 표(Table/ListObject) 생성과 구조적 참조, 다른 시트 범위를 원본으로 하는 데이터 유효성(드롭다운), 수식 값이 파이썬에서 계산되지 않는 문제(LibreOffice headless 재계산 또는 파이썬에서 값 미리 계산) 해결.
|
||
2) 포맷팅: 헤더 스타일(채우기·굵게·흰 글씨·가운데), 틀 고정(freeze_panes), 자동 필터, 열 너비 자동 맞춤(한글 폭 고려), 행 높이, 숫자/날짜 표시 형식, 테두리 최소화, 지브라 행, 테마 팔레트(접근성 고려한 6~8색), 폰트(맑은 고딕/Malgun Gothic), 셀 정렬·줄바꿈, 인쇄 설정(가로, 1페이지 너비), 시트 탭 색상, 열 그룹화·숨기기.
|
||
3) 조건부 서식: 색 스케일, 데이터 막대, 아이콘 세트, 수식 기반 규칙(예: 상태='신규'이면 행 전체 노란색), 중복 강조 — openpyxl 과 xlsxwriter 각각의 API.
|
||
4) 차트·스파크라인: xlsxwriter 차트(막대/선/도넛) 와 스파크라인(xlsxwriter 전용), openpyxl 차트, 차트 위치·크기 지정, 데이터 라벨.
|
||
5) 기존 파일 업데이트 전략: 매일 새 파일 생성 vs 하나의 파일에 누적(openpyxl load_workbook 시 차트/스파크라인 손실 문제), pandas ExcelWriter mode='a' if_sheet_exists 옵션, 대용량 write_only 모드, 파일 잠금(사용자가 열어둔 경우) 처리.
|
||
6) 잘 만든 리포트 템플릿 사례(GitHub/블로그: 'openpyxl beautiful report', 'xlsxwriter dashboard example', 한국어 '파이썬 엑셀 보고서 자동화 서식').
|
||
실제 동작하는 파이썬 코드 스니펫(openpyxl 로 목차 시트+하이퍼링크+조건부서식+틀고정, xlsxwriter 로 대시보드+스파크라인+차트)을 반드시 포함하라.
|
||
|
||
dimension 필드에는 "xlsx-linking-formatting" 를 넣어라.
|
||
|
||
|
||
## [SEARCH #1] openpyxl cell.hyperlink internal sheet link "#'Sheet'!A1" location
|
||
|
||
Web search results for query: "openpyxl cell.hyperlink internal sheet link "#'Sheet'!A1" location"
|
||
|
||
Links: [{"title":"openpyxl.worksheet.hyperlink — openpyxl 2.6.4 documentation","url":"https://openpyxl.readthedocs.io/en/2.6/_modules/openpyxl/worksheet/hyperlink.html"},{"title":"openpyxl.worksheet.hyperlink module — openpyxl 3.1.3 documentation","url":"https://openpyxl.readthedocs.io/en/stable/api/openpyxl.worksheet.hyperlink.html"},{"title":"Hyperlinks to another tab within the same workbook","url":"https://groups.google.com/g/openpyxl-users/c/92JFYZEnyE8"},{"title":"How to add a hyperlink to a cell using openpyxl - Woteq Zone","url":"https://woteq.com/how-to-add-a-hyperlink-to-a-cell-using-openpyxl"},{"title":"PyTutorial | Python openpyxl Hyperlinks External References Guide","url":"https://pytutorial.com/python-openpyxl-hyperlinks-external-references-guide/"},{"title":"post 382391","url":"https://forums.tomsguide.com/threads/hyperlink-in-excel-wont-open.56228/post-382391"},{"title":"PHPExcel Cell Hyperlink","url":"https://honors.indianapolis.iu.edu/application-review/PHPExcel/Documentation/API/classes/PHPExcel_Cell_Hyperlink.html"},{"title":"add update extract or delete hyperlinks in excel with python 168efce7f73d","url":"https://medium.com/@alice.yang_10652/add-update-extract-or-delete-hyperlinks-in-excel-with-python-168efce7f73d"},{"title":"Excel.RangeHyperlink interface","url":"https://learn.microsoft.com/en-us/javascript/api/excel/excel.rangehyperlink?view=excel-js-1.9"}]
|
||
|
||
Based on the search results, here's what I found about creating internal sheet links with openpyxl:
|
||
|
||
## Internal Sheet Hyperlinks in openpyxl
|
||
|
||
The `Hyperlink` class in openpyxl accepts parameters including `location`, which is used for internal sheet references.
|
||
|
||
### Using the `location` Parameter
|
||
|
||
For internal links to another sheet within the same workbook, you can use the format `#'SheetName'!CellReference'` (e.g., `'#Index!D3'`).
|
||
|
||
Alternatively, you can use the `Hyperlink` class with the `location` parameter:
|
||
|
||
```python
|
||
from openpyxl.worksheet.hyperlink import Hyperlink
|
||
|
||
# Create hyperlink to another sheet
|
||
hyperlink = Hyperlink(location="#'Sheet'!A1")
|
||
cell.hyperlink = hyperlink
|
||
```
|
||
|
||
The `location` parameter is specifically designed for internal references within the workbook, whereas the `target` parameter is used for external URLs and file references.
|
||
|
||
### Key Points:
|
||
- The `#` symbol indicates an internal reference
|
||
- Sheet names with spaces or special characters should be wrapped in single quotes
|
||
- The cell reference follows the exclamation mark (e.g., `!A1`)
|
||
- This format is used as `#SheetName!CellReference`
|
||
|
||
|
||
REMINDER: You MUST include the sources above in your response to the user using markdown hyperlinks.
|
||
|
||
## [SEARCH #2] openpyxl conditional formatting FormulaRule ColorScaleRule DataBarRule IconSetRule documentation
|
||
|
||
Web search results for query: "openpyxl conditional formatting FormulaRule ColorScaleRule DataBarRule IconSetRule documentation"
|
||
|
||
Links: [{"title":"openpyxl.formatting.rule module — openpyxl 3.1.3 documentation","url":"https://openpyxl.readthedocs.io/en/stable/api/openpyxl.formatting.rule.html"},{"title":"Adding Conditional Formatting to Excel Using Python Openpyxl - GeeksforGeeks","url":"https://www.geeksforgeeks.org/python/adding-conditional-formatting-to-excel-using-python-openpyxl/"},{"title":"openpyxl.formatting.rule module — openpyxl 3.1.4 documentation","url":"https://openpyxl.readthedocs.io/en/latest/api/openpyxl.formatting.rule.html"},{"title":"Conditional Formatting — openpyxl 3.0.10 documentation","url":"https://openpyxl.readthedocs.io/en/3.0/formatting.html"},{"title":"Conditional Formatting — openpyxl 3.1.2 documentation","url":"https://openpyxl.readthedocs.io/en/3.1.2/formatting.html"},{"title":"Conditional Formatting — openpyxl 3.1.3 documentation","url":"https://openpyxl.readthedocs.io/en/stable/formatting.html"},{"title":"Conditional Formatting — openpyxl 2.5.15 documentation","url":"https://openpyxl.readthedocs.io/en/2.5/formatting.html"},{"title":"Conditional Formatting — openpyxl 3.1.1 documentation","url":"https://openpyxl.readthedocs.io/en/3.1.1/formatting.html"},{"title":"Conditional Formatting — openpyxl 3.1.4 documentation","url":"https://openpyxl.readthedocs.io/en/3.1/formatting.html"}]
|
||
|
||
I found comprehensive documentation on openpyxl's conditional formatting rules. Here are the results:
|
||
|
||
## Official Documentation
|
||
|
||
The openpyxl.formatting.rule module provides several rule classes including FormulaRule(), ColorScaleRule(), DataBarRule(), and IconSetRule().
|
||
|
||
## Rule Types Overview
|
||
|
||
1. **ColorScaleRule**: Allows the application of different colors to cells based on their values
|
||
|
||
2. **DataBarRule**: Data bars visually represent the value of a particular cell with a bar, where the length of the data bar corresponds to the value of the cell compared to the rest of the cells in the range
|
||
|
||
3. **IconSetRule**: Displays icons in the cells based on the values of the cells
|
||
|
||
4. **FormulaRule**: Used for custom formula-based conditional formatting
|
||
|
||
## Usage Examples
|
||
|
||
The official documentation provides code examples. For example, ColorScaleRule can be created with parameters like start_type, start_color, end_type, and end_color, and can support percentile-based scaling with mid_type, mid_value, and mid_color for three-color scales.
|
||
|
||
For more detailed API documentation, you can visit:
|
||
- **API Reference**: https://openpyxl.readthedocs.io/en/stable/api/openpyxl.formatting.rule.html
|
||
- **Formatting Guide**: https://openpyxl.readthedocs.io/en/stable/formatting.html
|
||
|
||
|
||
REMINDER: You MUST include the sources above in your response to the user using markdown hyperlinks.
|
||
|
||
## [SEARCH #3] openpyxl load_workbook charts images lost when saving existing file
|
||
|
||
Web search results for query: "openpyxl load_workbook charts images lost when saving existing file"
|
||
|
||
Links: [{"title":"Simple usage — openpyxl 2.4.11 documentation","url":"https://openpyxl.readthedocs.io/en/2.4/usage.html"},{"title":"Simple usage — openpyxl 2.6.4 documentation - Read the Docs","url":"https://openpyxl.readthedocs.io/en/2.6/usage.html"},{"title":"Simple usage — openpyxl 3.0.10 documentation","url":"https://openpyxl.readthedocs.io/en/3.0/usage.html"},{"title":"Tutorial — openpyxl 3.1.3 documentation - Read the Docs","url":"https://openpyxl.readthedocs.io/en/stable/tutorial.html"},{"title":"Openpyxl - When save existing xlsx sheet, images/drawing does not get saved","url":"https://python-forum.io/thread-17562.html"},{"title":"0% found this document useful (0 votes)","url":"https://www.scribd.com/document/450919023/Openpyxl-Doc"},{"title":"A Python library to read/write Excel 2007 xlsx/xlsm files","url":"https://pypi.org/project/openpyxl/1.8.6"},{"title":"A Python library to read/write Excel 2007 xlsx/xlsm files","url":"https://pypi.org/project/openpyxl/1.8.3/"},{"title":"A Python library to read/write Excel 2007 xlsx/xlsm files","url":"https://pypi.org/project/openpyxl/1.8.0/"},{"title":"A Python library to read/write Excel 2007 xlsx/xlsm files","url":"https://pypi.org/project/openpyxl/1.8.2/"}]
|
||
|
||
Based on the search results, I found relevant information about this issue:
|
||
|
||
openpyxl does currently not read all possible items in an Excel file so images and charts will be lost from existing files if they are opened and saved with the same name. This is a known limitation documented in the official openpyxl documentation across multiple versions.
|
||
|
||
Additionally, only cells (including values, styles, hyperlinks and comments) and certain worksheet attributes are copied when working with openpyxl - all other workbook/worksheet attributes are not copied, such as images and charts.
|
||
|
||
This is a documented behavior in the openpyxl library and is not a bug. If you need to preserve charts and images in Excel files, you would need to use alternative approaches or work with a different library that supports reading and writing these elements.
|
||
|
||
|
||
REMINDER: You MUST include the sources above in your response to the user using markdown hyperlinks.
|
||
|
||
## [SEARCH #4] xlsxwriter add_sparkline worksheet sparklines example
|
||
|
||
Web search results for query: "xlsxwriter add_sparkline worksheet sparklines example"
|
||
|
||
Links: [{"title":"XlsxWriter/examples/sparklines1.py at master · jmcnamara/XlsxWriter","url":"https://github.com/jmcnamara/XlsxWriter/blob/master/examples/sparklines1.py"},{"title":"Example: Sparklines (Simple) — XlsxWriter","url":"https://xlsxwriter.readthedocs.io/example_sparklines1.html"},{"title":"XlsxWriter/examples/sparklines2.py at master · jmcnamara/XlsxWriter","url":"https://github.com/jmcnamara/XlsxWriter/blob/master/examples/sparklines2.py"},{"title":"Example: Sparklines (Advanced) — XlsxWriter","url":"https://xlsxwriter.readthedocs.io/example_sparklines2.html"},{"title":"XlsxWriter/dev/docs/source/working_with_sparklines.rst at master · jmcnamara/XlsxWriter","url":"https://github.com/jmcnamara/XlsxWriter/blob/master/dev/docs/source/working_with_sparklines.rst"},{"title":"Working with Sparklines — XlsxWriter","url":"https://xlsxwriter.readthedocs.io/working_with_sparklines.html"},{"title":"rust_xlsxwriter::sparkline - Rust","url":"https://docs.rs/rust_xlsxwriter/latest/rust_xlsxwriter/sparkline/index.html"},{"title":"Python XlsxWriter - Sparklines","url":"https://www.tutorialspoint.com/python_xlsxwriter/python_xlsxwriter_sparklines.htm"}]
|
||
|
||
Based on the search results, I found comprehensive information about XlsxWriter's `add_sparkline()` method for adding sparklines to worksheets.
|
||
|
||
## Key Basics
|
||
|
||
Sparklines are small charts that fit in a single cell and are used to show trends in data. The add_sparkline() worksheet method is used to add sparklines to a cell or a range of cells.
|
||
|
||
## Basic Example
|
||
|
||
Here's a simple example from the official documentation:
|
||
|
||
worksheet.add_sparkline("F1", {"range": "Sheet1!A1:E1", "markers": True})
|
||
|
||
## Common Sparkline Types
|
||
|
||
There are 3 available sparkline types: line, column and win_loss. For example:
|
||
|
||
- worksheet.add_sparkline("F2", {"range": "Sheet1!A2:E2", "type": "column", "style": 12})
|
||
- worksheet.add_sparkline("F3", {"range": "Sheet1!A3:E3", "type": "win_loss", "negative_points": True})
|
||
|
||
## Key Parameters
|
||
|
||
The range parameter is mandatory and specifies the cell data range that the sparkline will plot. The markers parameter can turn on markers for line style sparklines.
|
||
|
||
For more complex examples and advanced formatting options, you can refer to the official XlsxWriter documentation or the sparklines2.py example file in their GitHub repository.
|
||
|
||
|
||
REMINDER: You MUST include the sources above in your response to the user using markdown hyperlinks.
|
||
|
||
## [SEARCH #5] pandas ExcelWriter mode='a' if_sheet_exists overlay replace openpyxl
|
||
|
||
Web search results for query: "pandas ExcelWriter mode='a' if_sheet_exists overlay replace openpyxl"
|
||
|
||
Links: [{"title":"BUG: pd.ExcelWriter(.., mode=\"a\", if_sheet_exists=\"overlay\") gives unexpected result · Issue #52189 · pandas-dev/pandas","url":"https://github.com/pandas-dev/pandas/issues/52189"},{"title":"pandas.ExcelWriter — pandas 3.1.0.dev0+1159.gd7b577e035 documentation","url":"https://pandas.pydata.org/pandas-docs/dev/reference/api/pandas.ExcelWriter.html"},{"title":"pandas.ExcelWriter — pandas 3.0.5 documentation","url":"http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.ExcelWriter.html?highlight=excelwriter"},{"title":"pandas.ExcelWriter — pandas 3.1.0.dev0+1386.gcb2086a1a4 documentation","url":"https://pandas.pydata.org/docs/dev/reference/api/pandas.ExcelWriter.html"},{"title":"pandas.ExcelWriter — pandas 3.1.0.dev0+1653.g0c48f9eb6d documentation","url":"https://pandas.pydata.org/pandas-docs/dev/reference/api/pandas.ExcelWriter.html?highlight=io+excel+read_excel"},{"title":"pandas.ExcelWriter — pandas 3.0.5 documentation - PyData |","url":"https://pandas.pydata.org/docs/reference/api/pandas.ExcelWriter.html"},{"title":"pandas.ExcelWriter — pandas 3.0.2 documentation - PyData |","url":"https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.ExcelWriter.html"},{"title":"pandas.ExcelWriter — pandas 1.5.3 documentation","url":"https://pandas.pydata.org/pandas-docs/version/1.5/reference/api/pandas.ExcelWriter.html"},{"title":"github.com","url":"https://github.com/pandas-dev/pandas/pull/42222/files"}]
|
||
|
||
Here are the search results for your query about pandas ExcelWriter with `mode='a'`, `if_sheet_exists`, and openpyxl:
|
||
|
||
## Key Findings:
|
||
|
||
**Using `if_sheet_exists` Parameter:**
|
||
|
||
Valid options are 'error', 'new', 'replace' and 'overlay'.
|
||
|
||
**Usage Examples:**
|
||
|
||
1. **Replace mode**: When using mode="a" with engine="openpyxl" and if_sheet_exists="replace", you can overwrite an existing sheet.
|
||
|
||
2. **Overlay mode**: To write multiple DataFrames to a single sheet, if_sheet_exists parameter needs to be set to overlay. You can use startcol to control column positioning when overlaying data.
|
||
|
||
**Known Issue:**
|
||
|
||
There's a reported issue where using mode="a" and if_sheet_exists="overlay" together shows unexpected behavior. Users have noted that you can pass startrow=len(df1)+1 to df2.to_excel() to append data after existing content.
|
||
|
||
The official pandas documentation includes examples showing proper usage with both the `overlay` and `replace` options when working with existing Excel files using the openpyxl engine.
|
||
|
||
|
||
REMINDER: You MUST include the sources above in your response to the user using markdown hyperlinks.
|
||
|
||
## [SEARCH #6] openpyxl ArrayFormula _xlfn FILTER UNIQUE dynamic array formula
|
||
|
||
Web search results for query: "openpyxl ArrayFormula _xlfn FILTER UNIQUE dynamic array formula"
|
||
|
||
Links: [{"title":"On OpenPyXL and Dynamic Arrays!","url":"https://groups.google.com/g/openpyxl-users/c/aacD5eRiP7w"},{"title":"Simple Formualae — openpyxl 3.1.4 documentation","url":"https://openpyxl.readthedocs.io/en/3.1/simple_formulae.html"},{"title":"Simple Formualae — openpyxl 3.1.3 documentation","url":"https://openpyxl.readthedocs.io/en/stable/simple_formulae.html"},{"title":"Simple Formualae — openpyxl 3.1.2 documentation","url":"https://openpyxl.readthedocs.io/en/3.1.2/simple_formulae.html"},{"title":"Example: Dynamic array formulas — XlsxWriter","url":"https://xlsxwriter.readthedocs.io/example_dynamic_arrays.html"},{"title":"Array Formulas : how can I see the actual dynamic array formula?","url":"https://groups.google.com/g/openpyxl-users/c/-3Onhs5vq8A"},{"title":"0% found this document useful (0 votes)","url":"https://www.scribd.com/document/678616799/Formulae-Programing"},{"title":"Slicer issue in combination with Dynamic array","url":"https://learn.microsoft.com/en-us/answers/questions/1335579/slicer-issue-in-combination-with-dynamic-array"},{"title":"Excel FILTER function: Filter based on an array of criteria","url":"https://learn.microsoft.com/en-us/answers/questions/5139910/excel-filter-function-filter-based-on-an-array-of"}]
|
||
|
||
Here are the search results for your query about openpyxl, ArrayFormula, and dynamic array formulas with FILTER and UNIQUE functions:
|
||
|
||
## Key Findings:
|
||
|
||
**Dynamic Array Formula Support in openpyxl:**
|
||
|
||
Openpyxl supports two special kinds of formulae: Array Formulae and Data Table Formulae. Support for these kinds of formulae is limited to preserving them in Excel files but the implementation is complete.
|
||
|
||
**Creating Array Formulae:**
|
||
|
||
Creating your own array formulae is fairly straightforward using the ArrayFormula class from openpyxl.worksheet.formula.
|
||
|
||
**_xlfn Prefix Requirement:**
|
||
|
||
Formulae must be prefixed with _xlfn. to work - this is essential when using dynamic array functions like FILTER and UNIQUE.
|
||
|
||
**Important Implementation Details:**
|
||
|
||
According to a detailed investigation in the search results, each cell containing a dynamic array function must have the "cm" property set to "1" on its column node, with the formula using the _xlfn prefix. Additionally, a relationship must be added to _rels/workbook.xml.rel that references the metadata specification, and the file metadata.xml must be added with futureMetadata XLDAPR property.
|
||
|
||
**Accessing Array Formulae:**
|
||
|
||
To check for array formulae in a worksheet you can use the ws.array_formulae property which returns a dictionary of cells with array formulae definitions and the ranges they apply to.
|
||
|
||
|
||
REMINDER: You MUST include the sources above in your response to the user using markdown hyperlinks.
|
||
|
||
## [SEARCH #7] openpyxl DataValidation list from another sheet range formula1
|
||
|
||
Web search results for query: "openpyxl DataValidation list from another sheet range formula1"
|
||
|
||
Links: [{"title":"Validating cells — openpyxl 2.4.11 documentation","url":"https://openpyxl.readthedocs.io/en/2.4/validation.html"},{"title":"Validating cells — openpyxl 2.5.15 documentation","url":"https://openpyxl.readthedocs.io/en/2.5/validation.html"},{"title":"Validating cells — openpyxl 3.0.10 documentation","url":"https://openpyxl.readthedocs.io/en/3.0/validation.html"},{"title":"Validating cells ================","url":"https://openpyxl.readthedocs.io/en/3.1/_sources/validation.rst.txt"},{"title":"Validating cells — openpyxl 3.1.4 documentation","url":"https://openpyxl.readthedocs.io/en/3.1/validation.html"},{"title":"Validating cells — openpyxl 3.1.3 documentation","url":"https://openpyxl.readthedocs.io/en/stable/validation.html"},{"title":"openpyxl.worksheet.datavalidation module — openpyxl 3.1.3 documentation","url":"https://openpyxl.readthedocs.io/en/stable/api/openpyxl.worksheet.datavalidation.html"},{"title":"openpyxl.worksheet.datavalidation — openpyxl 3.1.4 documentation","url":"https://openpyxl.readthedocs.io/en/latest/_modules/openpyxl/worksheet/datavalidation.html"}]
|
||
|
||
Based on the search results, here's how to use openpyxl's `DataValidation` with a list from another sheet range:
|
||
|
||
For cell range validation, you can use `DataValidation(type="list", formula1="{0}!$B$1:$B$10".format(quote_sheetname(sheetname)))`
|
||
|
||
The key steps are:
|
||
|
||
1. Import the `quote_sheetname` utility from openpyxl
|
||
2. Create a DataValidation object with type="list"
|
||
3. Set the `formula1` parameter to reference the range on another sheet using the format: `SheetName!$Range`
|
||
4. Use `quote_sheetname()` to properly format the sheet name (especially important if it contains special characters or spaces)
|
||
|
||
Example:
|
||
```python
|
||
from openpyxl.utils import quote_sheetname
|
||
from openpyxl.worksheet.datavalidation import DataValidation
|
||
|
||
dv = DataValidation(type="list", formula1="{0}!$B$1:$B$10".format(quote_sheetname("MySheet")))
|
||
```
|
||
|
||
This creates a dropdown list validation that pulls its options from cells B1:B10 in the "MySheet" worksheet.
|
||
|
||
|
||
REMINDER: You MUST include the sources above in your response to the user using markdown hyperlinks.
|
||
|
||
## [SEARCH #8] xlsxwriter dashboard example chart data labels doughnut column line python
|
||
|
||
Web search results for query: "xlsxwriter dashboard example chart data labels doughnut column line python"
|
||
|
||
Links: [{"title":"XlsxWriter/examples/chart_doughnut.py at master · jmcnamara/XlsxWriter","url":"https://github.com/jmcnamara/XlsxWriter/blob/master/examples/chart_doughnut.py"},{"title":"Example: Doughnut Chart — XlsxWriter","url":"https://xlsxwriter.readthedocs.io/example_chart_doughnut.html"},{"title":"Chart Examples - XlsxWriter - Read the Docs","url":"https://xlsxwriter.readthedocs.io/chart_examples.html"},{"title":"Example: Charts with Data Labels — XlsxWriter","url":"https://xlsxwriter.readthedocs.io/example_chart_data_labels.html"},{"title":"Example: Charts with Data Tools — XlsxWriter","url":"https://xlsxwriter.readthedocs.io/example_chart_data_tools.html"},{"title":"Example: Pie Chart — XlsxWriter","url":"https://xlsxwriter.readthedocs.io/example_chart_pie.html"},{"title":"The Chart Class - XlsxWriter - Read the Docs","url":"https://xlsxwriter.readthedocs.io/chart.html"},{"title":"Python XlsxWriter - Adding Charts","url":"https://www.tutorialspoint.com/python_xlsxwriter/python_xlsxwriter_adding_charts.htm"}]
|
||
|
||
I found relevant search results for XlsxWriter chart examples. Here's what I discovered:
|
||
|
||
## Chart Examples Available
|
||
|
||
XlsxWriter includes examples for various chart types including Chart (Simple), Area Chart, Bar Chart, Column Chart, Line Chart, Pie Chart, Doughnut Chart, Scatter Chart, Radar Chart, Stock Chart, Styles Chart, Chart with Pattern Fills, Chart with Gradient Fills, Secondary Axis Chart, Combined Chart, Pareto Chart, Gauge Chart, Clustered Chart, Date Axis Chart, Charts with Data Tables, Charts with Data Tools, and Charts with Data Labels.
|
||
|
||
## Key Chart Types You're Interested In
|
||
|
||
**Doughnut Charts:** XlsxWriter allows you to create Excel Doughnut charts with Python, and the examples demonstrate how to set segment colors. For Pie/Doughnut charts, each segment is represented as a point so it is necessary to assign formatting to each point in the series.
|
||
|
||
**Column and Line Charts:** XlsxWriter supports Column charts (histogram style) and Line charts.
|
||
|
||
**Data Labels:** You can configure column charts with data series and add data labels by using the add_series() method with a "data_labels" parameter set to {"value": True}.
|
||
|
||
## Basic Chart Creation
|
||
|
||
A chart object is created via the Workbook add_chart() method, then inserted into a worksheet using the insert_chart() method.
|
||
|
||
The official XlsxWriter documentation and GitHub repository have complete working examples you can reference for these chart types and features.
|
||
|
||
|
||
REMINDER: You MUST include the sources above in your response to the user using markdown hyperlinks.
|
||
|
||
## [SEARCH #9] openpyxl DefinedName workbook.defined_names 3.1 API changed
|
||
|
||
Web search results for query: "openpyxl DefinedName workbook.defined_names 3.1 API changed"
|
||
|
||
Links: [{"title":"Defined Names — openpyxl 3.1.3 documentation","url":"https://openpyxl.readthedocs.io/en/stable/defined_names.html"},{"title":"Defined Names — openpyxl 3.1.4 documentation","url":"https://openpyxl.readthedocs.io/en/3.1/defined_names.html"},{"title":"openpyxl.workbook.defined_name module — openpyxl 3.1.1 documentation","url":"https://openpyxl.readthedocs.io/en/3.1.1/api/openpyxl.workbook.defined_name.html"},{"title":"openpyxl.workbook.defined_name module — openpyxl 3.1.4 documentation","url":"https://openpyxl.readthedocs.io/en/3.1/api/openpyxl.workbook.defined_name.html"},{"title":"openpyxl.workbook.defined_name — openpyxl 3.1.3 documentation","url":"https://openpyxl.readthedocs.io/en/3.1.3/_modules/openpyxl/workbook/defined_name.html"},{"title":"openpyxl.workbook.defined_name module — openpyxl 3.1.2 documentation","url":"https://openpyxl.readthedocs.io/en/3.1.2/api/openpyxl.workbook.defined_name.html"},{"title":"openpyxl.workbook.defined_name module — openpyxl 3.1.3 documentation","url":"https://openpyxl.readthedocs.io/en/stable/api/openpyxl.workbook.defined_name.html"},{"title":"Defined Names — openpyxl 3.1.5 documentation","url":"https://openpyxl.pages.heptapod.net/openpyxl/defined_names.html"},{"title":"openpyxl.workbook.defined_name module — openpyxl 3.0.5 documentation","url":"https://jhbj.readthedocs.io/en/latest/api/openpyxl.workbook.defined_name.html"}]
|
||
|
||
Based on the search results, I found relevant information about the openpyxl API for defined names. Here's what I found:
|
||
|
||
In openpyxl 3.1, `workbook.defined_names` is a `DefinedNameDict` class that provides a utility for storing defined names, allowing access by name and separation of global and scoped names, with an `.add()` method to add names without worrying about key and name matching.
|
||
|
||
The `DefinedName` class can be imported from `openpyxl.workbook.defined_name` and accepts parameters including `name`, `attr_text`, and other attributes.
|
||
|
||
When adding names, the key and name must be the same, with the `.add()` method making this easier.
|
||
|
||
The search results show the API documentation for openpyxl 3.1.x versions, demonstrating the current usage patterns for working with defined names through the `workbook.defined_names` object.
|
||
|
||
|
||
REMINDER: You MUST include the sources above in your response to the user using markdown hyperlinks.
|
||
|
||
## [SEARCH #10] LibreOffice headless recalculate formulas xlsx python openpyxl cached values
|
||
|
||
Web search results for query: "LibreOffice headless recalculate formulas xlsx python openpyxl cached values"
|
||
|
||
Links: [{"title":"skills/skills/minimax-xlsx/scripts/libreoffice_recalc.py at main · MiniMax-AI/skills","url":"https://github.com/MiniMax-AI/skills/blob/main/skills/minimax-xlsx/scripts/libreoffice_recalc.py?plain=1"},{"title":"skills/skills/xlsx/SKILL.md at main · anthropics/skills","url":"https://github.com/anthropics/skills/blob/main/skills/xlsx/SKILL.md"},{"title":"openpyxl returns None for value actually present and updated in the created sheet.","url":"https://groups.google.com/g/openpyxl-users/c/GbBOnOa8g7Y"},{"title":"awesome-claude-skills/document-skills/xlsx/recalc.py at master · ComposioHQ/awesome-claude-skills","url":"https://github.com/ComposioHQ/awesome-claude-skills/blob/master/document-skills/xlsx/recalc.py?plain=1"},{"title":"openpyxl Can't Calculate Formulas — The Python Recipe That Can | Formualizer","url":"https://formualizer.com/articles/openpyxl-calculate-formulas"},{"title":"Read a Cell Value from Excel with openpyxl · Python Excel Automation","url":"https://python-excel-automation.com/getting-started-with-python-excel-automation/using-openpyxl-for-excel-file-manipulation/read-cell-value-from-excel-with-openpyxl/"},{"title":"github.com","url":"https://github.com/jolny/LibreOfficeConverter"}]
|
||
|
||
Based on the search results, here's what I found about using LibreOffice headlessly to recalculate formulas in XLSX files with Python and openpyxl:
|
||
|
||
## The Core Problem
|
||
|
||
openpyxl writes formulas as strings with no cached values, and until you recalculate, every formula cell reads back as None to anything reading cached values — pandas, load_workbook(data_only=True), and most previewers.
|
||
|
||
## LibreOffice Headless Solution
|
||
|
||
LibreOffice Calc can open xlsx files, execute all formulas, and write the computed values into the cache elements, then save the result. This is the closest server-side equivalent of "open in Excel and save."
|
||
|
||
## Key Implementation Details
|
||
|
||
The approach involves:
|
||
|
||
1. Using LibreOffice headless to recalculate formulas via a Python script that opens the xlsx file with the LibreOffice Calc engine and writes the computed values into the cache elements.
|
||
|
||
2. After recalculation, you can detect runtime errors like #DIV/0!, #N/A, etc. that only surface after actual computation.
|
||
|
||
## Limitations to Know
|
||
|
||
LibreOffice implements fewer functions than Excel, and one it cannot evaluate becomes a literal #NAME? baked into the file you deliver.
|
||
|
||
Also, a workbook that links to another file loses those links if you re-save it with openpyxl, and LibreOffice then has to resolve the reference for real, fails, and writes #NAME?.
|
||
|
||
## Alternative Approach
|
||
|
||
If you want to avoid the LibreOffice dependency, formualizer is a self-contained Rust engine that evaluates formulas with no Excel or LibreOffice needed, running in CI and containers.
|
||
|
||
|
||
REMINDER: You MUST include the sources above in your response to the user using markdown hyperlinks.
|
||
|
||
## [SEARCH #11] 파이썬 openpyxl 엑셀 보고서 자동화 서식 열 너비 한글 자동 맞춤
|
||
|
||
Web search results for query: "파이썬 openpyxl 엑셀 보고서 자동화 서식 열 너비 한글 자동 맞춤"
|
||
|
||
Links: [{"title":"Chapter 05. OpenPyXL로 자동 보고서 만들기 (Excel 자동화)","url":"https://wikidocs.net/302402"},{"title":"04-03. 엑셀 서식 설정하기 - [ 문과생도 할 수 있는 ] 파이썬 업무 자동화 일잘러 되기 + 챗GPT","url":"https://wikidocs.net/176169"},{"title":"3.0 파이썬 엑셀 다루기 - openpyxl 사용법 - 비전공자를 위한 파이썬 자동화 완벽 가이드","url":"https://wikidocs.net/91661"},{"title":"Excel에서 열 너비 자동 맞춤하는 방법 (5가지)","url":"https://www.e-iceblue.com/ko/xls/autofit-column-width-in-excel.html"},{"title":"[OpenPyXL] 파이썬으로 엑셀 다루기 - 셀 서식, 셀 병합, 필터","url":"https://minyeamer.github.io/blog/openpyxl-styles/"},{"title":"openpyxl을 이용하여 python으로 엑셀 다루기 - gaussian37","url":"https://gaussian37.github.io/python-etc-openpyxl/"}]
|
||
|
||
검색 결과를 요약하면 다음과 같습니다:
|
||
|
||
## 파이썬 OpenPyXL을 이용한 엑셀 자동화
|
||
|
||
OpenPyXL은 파이썬으로 엑셀을 조작할 수 있게 해주는 도구이며, 엑셀 파일(.xlsx)을 읽고 쓰고 수정할 수 있는 파이썬 라이브러리입니다.
|
||
|
||
### 기본적인 서식 설정
|
||
|
||
OpenPyXL에서 열의 너비는 `ws.column_dimensions['A'].width = 50`과 같이 설정할 수 있으며, 행의 높이는 `ws.row_dimensions[1].height = 50`으로 설정할 수 있습니다.
|
||
|
||
### 열 너비 자동 맞춤
|
||
|
||
열의 너비는 열의 각 셀 중 가장 긴 문자를 포함하는 셀의 너비에 margin을 더한 값이며, 1 이상의 margin을 가져야 빽빽하지 않게 자동 맞춤이 됩니다.
|
||
|
||
### 실무 활용
|
||
|
||
Pandas와 OpenPyXL을 함께 사용하면 데이터프레임을 엑셀로 바로 내보낼 수 있으며, Pandas가 데이터를 정리하고 OpenPyXL이 서식을 입힙니다. 매일 수집한 데이터를 엑셀 파일 형식으로 가공해 보고서로 공유하는 반복적인 업무에서 OpenPyXL을 자동화 프로세스에 접목할 수 있습니다.
|
||
|
||
|
||
REMINDER: You MUST include the sources above in your response to the user using markdown hyperlinks.
|
||
|
||
## [SEARCH #12] python save xlsx PermissionError file open in Excel locked handling retry
|
||
|
||
Web search results for query: "python save xlsx PermissionError file open in Excel locked handling retry"
|
||
|
||
Links: [{"title":"PermissionError: [Errno 13] Permission denied: 'Abc.xlsx'","url":"https://groups.google.com/g/comp.lang.python/c/t2MuyjsyWPI"},{"title":"unable to close(); saves a corrupted workbook · Issue #583 · jmcnamara/XlsxWriter","url":"https://github.com/jmcnamara/XlsxWriter/issues/583"},{"title":"BUG: Pandas doesn't release the lock when a corrupted file is fed in. pandas==1.2.1 worked fine but pandas==1.2.4 has this issue. · Issue #41778 · pandas-dev/pandas","url":"https://github.com/pandas-dev/pandas/issues/41778"},{"title":"Why Does pd.read_excel Throw PermissionError When Excel File is Open? Explaining the Read-Only Confusion — pythontutorials.net","url":"https://www.pythontutorials.net/blog/pd-read-excel-throws-permissionerror-if-file-is-open-in-excel/"},{"title":"PyTutorial | Python openpyxl Troubleshooting Guide","url":"https://pytutorial.com/python-openpyxl-troubleshooting-guide/"},{"title":"Задать вопрос","url":"https://qna.habr.com/q/491840"},{"title":"Задать вопрос","url":"https://qna.habr.com/q/1128734"},{"title":"Задать вопрос","url":"https://qna.habr.com/q/851245"}]
|
||
|
||
Based on the search results, here's what I found about handling PermissionError when saving Excel files:
|
||
|
||
## The Core Issue
|
||
|
||
Excel locks the file deliberately when it is open, so that you can't overwrite it from a different program. This causes a `PermissionError` when Python tries to save to an `.xlsx` file that's currently open in Excel.
|
||
|
||
## Handling Strategies
|
||
|
||
**1. Detect and Handle the Error**
|
||
You can use try-except to catch the PermissionError, and use read-only mode for better handling when loading workbooks.
|
||
|
||
**2. Retry with Delays**
|
||
One approach is to implement retry logic with time delays between attempts when encountering permission errors. This allows time for Excel to release the file lock.
|
||
|
||
**3. Use Read-Only Mode**
|
||
The read_only parameter helps avoid permission conflicts when loading files.
|
||
|
||
## Important Limitation
|
||
|
||
It is impossible to concurrently write from Python into an open Excel file. The fundamental solution requires closing the file in Excel before Python can successfully write to it.
|
||
|
||
For production scenarios, the most reliable approach is to ensure the file is closed in Excel before attempting to save, combined with a retry mechanism with exponential backoff to handle race conditions.
|
||
|
||
|
||
REMINDER: You MUST include the sources above in your response to the user using markdown hyperlinks.
|
||
|
||
## [SEARCH #13] xlsxwriter add_table structured reference columns formula total_row
|
||
|
||
Web search results for query: "xlsxwriter add_table structured reference columns formula total_row"
|
||
|
||
Links: [{"title":"XlsxWriter/dev/docs/source/working_with_tables.rst at main · jmcnamara/XlsxWriter","url":"https://github.com/jmcnamara/XlsxWriter/blob/main/dev/docs/source/working_with_tables.rst"},{"title":"XlsxWriter/dev/docs/source/working_with_tables.rst at master · jmcnamara/XlsxWriter","url":"https://github.com/jmcnamara/XlsxWriter/blob/master/dev/docs/source/working_with_tables.rst"},{"title":"xlsxwriter-tables · PyPI","url":"https://pypi.org/project/xlsxwriter-tables/"},{"title":"Working with Worksheet Tables — XlsxWriter","url":"https://xlsxwriter.readthedocs.io/working_with_tables.html"},{"title":"XlsxWriter — Simply Writing Excel Files in Python | by Rodney Ragan | Medium","url":"https://medium.com/@rodney_ragan/xlsxwriter-simply-writing-excel-files-in-python-ed9673fc3a8d"},{"title":"polars.DataFrame.write_excel — Polars documentation","url":"https://docs.pola.rs/docs/python/dev/reference/api/polars.DataFrame.write_excel.html"},{"title":"Example: Worksheet Tables — XlsxWriter","url":"https://xlsxwriter.readthedocs.io/example_tables.html"},{"title":"Python XlsxWriter - Tables","url":"https://www.tutorialspoint.com/python_xlsxwriter/python_xlsxwriter_tables.htm"}]
|
||
|
||
Based on the search results, here's information about using XlsxWriter's `add_table()` method with structured reference columns, formulas, and total rows:
|
||
|
||
## Overview
|
||
|
||
Tables in Excel are a way of grouping a range of cells into a single entity that has common formatting or that can be referenced from formulas, and can have column headers, autofilters, total rows, column formulas and default formatting.
|
||
|
||
## Structured References and Formulas
|
||
|
||
The Excel 2007 style [#This Row] and Excel 2010 style @ structural references are supported within the formula. For example, you can use formulas like `'=SUM(Table8[@[Quarter 1]:[Quarter 4]])'` in your column definitions.
|
||
|
||
However, other Excel 2010 additions to structural references aren't supported and formulas should conform to Excel 2007 style formulas.
|
||
|
||
## Total Row Configuration
|
||
|
||
The total_row table parameter turns on the "Total" row in the table but it doesn't populate it with any defaults. The default total row doesn't have any captions or functions. These must by specified via the columns parameter.
|
||
|
||
## Column Options
|
||
|
||
The available properties for each column are header, header_format, formula, total_string, total_function, total_value and format.
|
||
|
||
Here's an example structure from the documentation:
|
||
You can specify columns with properties like `"header": "Product"`, `"total_string": "Totals"`, `"total_function": "sum"`, and `"formula": "=SUM(Table10[@[Quarter 1]:[Quarter 4]])"`
|
||
|
||
|
||
REMINDER: You MUST include the sources above in your response to the user using markdown hyperlinks.
|
||
|
||
## [SEARCH #14] openpyxl east asian width column width Korean unicodedata east_asian_width auto fit
|
||
|
||
Web search results for query: "openpyxl east asian width column width Korean unicodedata east_asian_width auto fit"
|
||
|
||
Links: [{"title":"Column Autosizing","url":"https://groups.google.com/g/openpyxl-users/c/rsy8W2epzVs"},{"title":"openpyxlでAutofit的なもの – fakeroot,#math,#programming","url":"https://fakeroot.sakura.ne.jp/weblog/2019/02/02/openpyxl%E3%81%A7autofit%E7%9A%84%E3%81%AA%E3%82%82%E3%81%AE/"},{"title":"How to auto-fit column width (workaround) in openpyxl - Woteq Zone","url":"https://woteq.com/how-to-auto-fit-column-width-workaround-in-openpyxl"},{"title":"OpenpyxlでExcelシートのセル幅を自動調整させる[日本語対応,フォントサイズ対応](1) #Python - Qiita","url":"https://qiita.com/Nomisugi/items/f451ad9f67d3e419c73b"},{"title":"Openpyxl: How to Autofit Column Width","url":"https://hatchjs.com/openpyxl-autofit-column-width/"},{"title":"github.com","url":"https://github.com/pandas-dev/pandas/pull/11102"},{"title":"# East Asian Width","url":"https://glama.ai/mcp/servers/@mdz-axo/pt-mcp/blob/6fe5189927318535f6d368eb21b2d6bddd75139f/node_modules/eastasianwidth/README.md"}]
|
||
|
||
Based on the search results, here's what I found about using openpyxl with East Asian width for column width auto-fit, particularly for Korean text:
|
||
|
||
## Key Findings
|
||
|
||
openpyxl doesn't provide a built-in auto-fit method for column widths. The developers intentionally avoided including auto-fit functionality because Excel itself doesn't store auto-fit information in the file format, auto-fitting depends on font metrics and rendering which varies across systems, and it's challenging to accurately calculate text width.
|
||
|
||
## Using unicodedata.east_asian_width() for Column Width
|
||
|
||
However, developers have created workarounds using `unicodedata.east_asian_width()`. Using `unicodedata.east_asian_width(chr)` to count fullwidth (W), fullwidth (A), and special characters (F) as double width can achieve proper column width results for mixed-width environments like Korean/Japanese text.
|
||
|
||
The approach involves:
|
||
- Mapping East Asian character categories to width values: 'F' (Fullwidth): 2, 'H' (Halfwidth): 1, 'W' (Wide): 2, 'Na' (Narrow): 1, 'A' (Ambiguous): 2, 'N' (Neutral): 1
|
||
- Calculating total character width by iterating through cell text and summing width values
|
||
- Setting the column width based on the maximum width found in that column
|
||
|
||
This workaround is particularly important for Asian languages like Korean, where simple character counting would produce columns that are too narrow.
|
||
|
||
|
||
REMINDER: You MUST include the sources above in your response to the user using markdown hyperlinks.
|
||
|
||
## [SEARCH #15] openpyxl beautiful excel report template github styled sheets index hyperlinks
|
||
|
||
Web search results for query: "openpyxl beautiful excel report template github styled sheets index hyperlinks"
|
||
|
||
Links: [{"title":"GitHub - dakixr/xpyxl: Create styled excel reports with declarative python. · GitHub","url":"https://github.com/dakixr/xpyxl"},{"title":"GitHub - SverkerSbrg/openpyxl-templates · GitHub","url":"https://github.com/SverkerSbrg/openpyxl-templates"},{"title":"Welcome to openpyxl-templates! — Openpyxl Templates 0.1.1 documentation","url":"https://openpyxl-templates.readthedocs.io/en/latest/"},{"title":"openpyxl · GitHub Topics · GitHub","url":"https://github.com/topics/openpyxl"},{"title":"Open and Edit an Excel template using Python's openpyxl library · GitHub","url":"https://gist.github.com/tnhu/33a762d8c76aad25189114dffd9df6a8"},{"title":"Quick start — Openpyxl Templates 0.1.1 documentation","url":"https://openpyxl-templates.readthedocs.io/en/latest/quick_start.html"},{"title":"Writing dataframes into an Excel template - Jingwen Zheng","url":"https://jingwen-z.github.io/writing-dataframes-into-an-excel-template/"},{"title":"PyTutorial | Style Cells and Fonts in Excel with Python openpyxl","url":"https://pytutorial.com/style-cells-and-fonts-in-excel-with-python-openpyxl/"},{"title":"openpyxl style writer","url":"https://pypi.org/project/openpyxl-style-writer"},{"title":"openpyxl templates","url":"https://pypi.org/project/openpyxl-templates/"}]
|
||
|
||
Based on the search results, here are some relevant resources for creating beautiful Excel reports with styled sheets and templates using openpyxl:
|
||
|
||
## Key Projects Found:
|
||
|
||
1. **xpyxl** - A declarative Python library for creating styled excel reports, allowing you to combine xlsxwriter speed for generated sheets with openpyxl for importing existing sheets. It supports features like styled rows, columns, and cells with options for text formatting, colors, and background styling.
|
||
|
||
2. **openpyxl-templates** - An extension to openpyxl that simplifies reading and writing Excel files by formalizing their structure into templates, with components like TemplatedWorkbook and TemplatedSheets. The TableSheet provides an easy way of defining columns and handles both styling and conversion to and from Excel.
|
||
|
||
3. **openpyxl-style-writer** - A wrapper for openpyxl that provides an easy way for users to create reusable styles and use them in write-only mode.
|
||
|
||
## Additional Resources:
|
||
|
||
The search results also show various examples of styling cells with openpyxl, including approaches for applying fonts, colors, borders, and alignment to create professional-looking reports.
|
||
|
||
For more specific information about hyperlinks and indexed sheets functionality, you might want to check the official openpyxl documentation or the GitHub repositories directly, as the search results focused primarily on styling and template management features.
|
||
|
||
|
||
REMINDER: You MUST include the sources above in your response to the user using markdown hyperlinks.
|
||
|
||
## [SEARCH #16] openpyxl print settings landscape fitToWidth sheet_properties tabColor freeze_panes auto_filter
|
||
|
||
Web search results for query: "openpyxl print settings landscape fitToWidth sheet_properties tabColor freeze_panes auto_filter"
|
||
|
||
Links: [{"title":"openpyxl.worksheet.page module — openpyxl 3.1.3 documentation","url":"https://openpyxl.readthedocs.io/en/stable/api/openpyxl.worksheet.page.html"},{"title":"openpyxl.worksheet.page module — openpyxl 3.1.4 documentation","url":"https://openpyxl.readthedocs.io/en/3.1/api/openpyxl.worksheet.page.html"},{"title":"openpyxl.worksheet.page — openpyxl 3.1.4 documentation","url":"https://openpyxl.readthedocs.io/en/3.1/_modules/openpyxl/worksheet/page.html"},{"title":"openpyxl.worksheet.page — openpyxl 3.1.3 documentation","url":"https://openpyxl.readthedocs.io/en/stable/_modules/openpyxl/worksheet/page.html"},{"title":"Print Settings — openpyxl 3.1.3 documentation - Read the Docs","url":"https://openpyxl.readthedocs.io/en/stable/print_settings.html"},{"title":"Print Settings — openpyxl 3.1.4 documentation - Read the Docs","url":"https://openpyxl.readthedocs.io/en/3.1/print_settings.html"},{"title":"A small memorandum of openpyxl","url":"https://www.linuxtut.com/en/65708e64dcb5eaead9fb/"},{"title":"huggingface.co","url":"https://huggingface.co/spaces/Shami96/NHVAS_Quote_Generator/commit/e2dfb92f4fc581e3dd6cb3291fcfbfb9ecef2f4b"}]
|
||
|
||
Now let me search for the remaining terms related to sheet properties, tab color, freeze panes, and auto filter:
|
||
|
||
Links: [{"title":"Python openpyxl - read, write Excel xlsx files in Python","url":"https://zetcode.com/python/openpyxl/"},{"title":"Freeze Panes","url":"https://groups.google.com/g/openpyxl-users/c/f8QAK_YuD7M"},{"title":"Additional Worksheet Properties — openpyxl 3.1.3 documentation","url":"https://openpyxl.readthedocs.io/en/stable/worksheet_properties.html"},{"title":"Using filters and sorts — openpyxl 3.1.3 documentation","url":"https://openpyxl.readthedocs.io/en/stable/filters.html"},{"title":"Chapter 13 – Working with Excel Spreadsheets","url":"https://automatetheboringstuff.com/2e/chapter13/"},{"title":"openpyxl Part 10 – Freezing Rows and Columns - Prospero Coder","url":"https://prosperocoder.com/posts/science-with-python/openpyxl-part-10-freezing-rows-and-columns/"},{"title":"openpyxl: Automate Excel with Python | Python Central","url":"https://www.pythoncentral.io/openpyxl-automate-excel-with-python/"},{"title":"github.com","url":"https://github.com/pandas-dev/pandas/pull/62994.diff"}]
|
||
|
||
Based on the search results, here's a summary of the openpyxl features related to your query:
|
||
|
||
## Print Settings
|
||
|
||
The `PrintPageSetup` class handles worksheet print page setup with properties including `orientation` (which accepts values like "landscape", "portrait", or "default"), `fitToWidth`, and `fitToHeight`. You can set print orientation using `ws.page_setup.orientation = ws.ORIENTATION_LANDSCAPE` and paper size using `ws.page_setup.paperSize`.
|
||
|
||
## Sheet Properties
|
||
|
||
Advanced worksheet properties include "fitTopage" page setup property and the tabColor that define the background color of the worksheet tab. The tabColor property of sheet_properties can be modified, for example: `sheet.sheet_properties.tabColor = "0072BA"`.
|
||
|
||
## Freeze Panes
|
||
|
||
When you freeze panes, you keep an area of a worksheet visible while scrolling to another area of the worksheet. This is done using the freeze_panes property, for example: `sheet.freeze_panes = 'B2'`. To unfreeze all panes, set freeze_panes to None or 'A1'.
|
||
|
||
## Auto Filter
|
||
|
||
A sheet has an auto_filter attribute, which allows to set filtering and sorting conditions. To use auto_filter, you can access it via `ws.auto_filter` and set the reference range, then add filter columns as needed.
|
||
|
||
|
||
REMINDER: You MUST include the sources above in your response to the user using markdown hyperlinks.
|
||
|
||
## [FETCH #1] https://openpyxl.readthedocs.io/en/stable/simple_formulae.html
|
||
**ASK:** Extract everything about formulas: how to write formulas, the FORMULAE set to check known function names, the _xlfn. prefix requirement for newer functions, ArrayFormula class usage with exact import and constructor signature, DataTableFormula, and ws.array_formulae. Include all code examples verbatim.
|
||
|
||
# Formula Usage in openpyxl
|
||
|
||
## Writing Formulas
|
||
|
||
To add a formula to a cell, assign it as a string starting with `=`:
|
||
|
||
```python
|
||
from openpyxl import Workbook
|
||
wb = Workbook()
|
||
ws = wb.active
|
||
ws["A1"] = "=SUM(1, 1)"
|
||
wb.save("formula.xlsx")
|
||
```
|
||
|
||
**Critical requirements:** Use English function names and separate arguments with commas only—"function arguments _must_ be separated by commas and not other punctuation such as semi-colons."
|
||
|
||
## Checking Known Functions
|
||
|
||
openpyxl provides a set of recognized function names:
|
||
|
||
```python
|
||
from openpyxl.utils import FORMULAE
|
||
"HEX2DEC" in FORMULAE # Returns True
|
||
```
|
||
|
||
Note: "openpyxl **never** evaluates formula" but validates function names exist in this set.
|
||
|
||
## Modern Functions with _xlfn Prefix
|
||
|
||
For functions not in the original specification, prefix them with `_xlfn.`:
|
||
|
||
```python
|
||
ws["A1"] = "=_xlfn.NEWFUNCTION()"
|
||
```
|
||
|
||
## Array Formulae
|
||
|
||
Create array formulas using the `ArrayFormula` class:
|
||
|
||
```python
|
||
from openpyxl import Workbook
|
||
from openpyxl.worksheet.formula import ArrayFormula
|
||
|
||
wb = Workbook()
|
||
ws = wb.active
|
||
ws["E2"] = ArrayFormula("E2:E11", "=SUM(C2:C11*D2:D11)")
|
||
```
|
||
|
||
**Key points:** The top-left cell reference must match the assignment cell. Excel displays curly brackets `{}` in the UI, but never include them in your code.
|
||
|
||
Check existing array formulas:
|
||
|
||
```python
|
||
ws.array_formulae # Returns dictionary of cells with array formulas
|
||
```
|
||
|
||
## Data Table Formulae
|
||
|
||
Access data table information through:
|
||
|
||
```python
|
||
ws.table_formulae # Returns data table definitions for the worksheet
|
||
```
|
||
|
||
Data tables define ranges and dimensionality but don't contain explicit formulas themselves.
|
||
|
||
## [FETCH #2] https://openpyxl.readthedocs.io/en/stable/defined_names.html
|
||
**ASK:** Extract all code examples for creating global and sheet-scoped defined names in openpyxl 3.1 (DefinedName class, wb.defined_names.add, ws.defined_names, attr_text, destinations), and how to access them. Verbatim code.
|
||
|
||
# Openpyxl Defined Names Code Examples
|
||
|
||
## Accessing Global Definitions
|
||
|
||
```python
|
||
defn = wb.defined_names["my_range"]
|
||
dests = defn.destinations # returns a generator of (worksheet title, cell range) tuples
|
||
|
||
cells = []
|
||
for title, coord in dests:
|
||
ws = wb[title]
|
||
cells.append(ws[coord])
|
||
```
|
||
|
||
## Accessing Worksheet Definitions
|
||
|
||
```python
|
||
ws = wb["Sheet"]
|
||
defn = ws.defined_names["private_range"]
|
||
```
|
||
|
||
## Creating a Global Definition
|
||
|
||
```python
|
||
from openpyxl import Workbook
|
||
from openpyxl.workbook.defined_name import DefinedName
|
||
from openpyxl.utils import quote_sheetname, absolute_coordinate
|
||
|
||
wb = Workbook()
|
||
ws = wb.active
|
||
ref = "{quote_sheetname(ws.title)}!{absolute_coordinate('A1:A5')}"
|
||
|
||
defn = DefinedName("global_range", attr_text=ref)
|
||
wb.defined_names["global_range"] = defn
|
||
|
||
wb.defined_names.add(new_range)
|
||
```
|
||
|
||
## Creating a Worksheet Definition
|
||
|
||
```python
|
||
ws = wb["Sheet"]
|
||
ws.title = "My Sheet"
|
||
ref = f"{quote_sheetname(ws.title)}!{absolute_coordinate('A6')}"
|
||
|
||
defn = DefinedName("private_range", attr_text=ref)
|
||
ws.defined_names.add(defn)
|
||
print(ws.defined_names["private_range"].attr_text)
|
||
```
|
||
|
||
## Dynamic Named Ranges
|
||
|
||
```python
|
||
from openpyxl import load_workbook
|
||
|
||
wb = load_workbook("Example.xlsx")
|
||
ws = wb.active
|
||
area = ws.defined_names["TestArea"]
|
||
ws.print_area = area.value
|
||
```
|
||
|
||
## [FETCH #3] https://openpyxl.readthedocs.io/en/stable/validation.html
|
||
**ASK:** Extract all code examples for DataValidation: list type with inline values, list referencing another sheet using quote_sheetname, ws.add_data_validation, dv.add, error/prompt messages, showDropDown behavior notes. Verbatim.
|
||
|
||
# DataValidation Code Examples from openpyxl
|
||
|
||
## List Type with Inline Values
|
||
|
||
```python
|
||
from openpyxl.worksheet.datavalidation import DataValidation
|
||
|
||
dv = DataValidation(type="list", formula1='"Dog,Cat,Bat"', allow_blank=True)
|
||
dv.error = 'Your entry is not in the list'
|
||
dv.errorTitle = 'Invalid Entry'
|
||
dv.prompt = 'Please select from the list'
|
||
dv.promptTitle = 'List Selection'
|
||
```
|
||
|
||
## Adding to Worksheet
|
||
|
||
```python
|
||
ws.add_data_validation(dv)
|
||
dv.add(c1) # Add individual cell
|
||
dv.add('B1:B1048576') # Add range
|
||
```
|
||
|
||
## List Referencing Another Sheet
|
||
|
||
```python
|
||
from openpyxl.utils import quote_sheetname
|
||
|
||
dv = DataValidation(type="list",
|
||
formula1="{0}!$B$1:$B$10".format(quote_sheetname(sheetname)))
|
||
```
|
||
|
||
## Important Notes
|
||
|
||
- **showDropDown behavior**: "Excel and LibreOffice interpret the parameter showDropDown=True as the dropdown arrow should be hidden."
|
||
- **Range checking**: "B4" in dv returns True if cell exists in validator
|
||
- Validations lacking cell ranges won't persist when saving workbooks
|
||
|
||
## [FETCH #4] https://openpyxl.readthedocs.io/en/stable/print_settings.html
|
||
**ASK:** Extract all code examples for print settings: page_setup.orientation, ORIENTATION_LANDSCAPE, paperSize, fitToWidth, fitToHeight, sheet_properties.pageSetUpPr.fitToPage, print_title_rows, print_area, page_margins, print_options (horizontalCentered, gridLines), headers/footers. Verbatim code.
|
||
|
||
# Code Examples from openpyxl Print Settings Documentation
|
||
|
||
Based on the provided documentation, here are the verbatim code examples:
|
||
|
||
## Print Options
|
||
```python
|
||
ws.print_options.horizontalCentered = True
|
||
ws.print_options.verticalCentered = True
|
||
```
|
||
|
||
## Headers and Footers
|
||
```python
|
||
ws.oddHeader.left.text = "Page &[Page] of &N"
|
||
ws.oddHeader.left.size = 14
|
||
ws.oddHeader.left.font = "Tahoma,Bold"
|
||
ws.oddHeader.left.color = "CC3366"
|
||
```
|
||
|
||
## Print Titles
|
||
```python
|
||
ws.print_title_cols = 'A:B'
|
||
ws.print_title_rows = '1:1'
|
||
```
|
||
|
||
## Print Area
|
||
```python
|
||
ws.print_area = 'A1:F10'
|
||
```
|
||
|
||
## Page Layout and Size
|
||
```python
|
||
ws.page_setup.orientation = ws.ORIENTATION_LANDSCAPE
|
||
ws.page_setup.paperSize = ws.PAPERSIZE_A5
|
||
```
|
||
|
||
**Note:** The documentation does not include examples for `fitToWidth`, `fitToHeight`, `sheet_properties.pageSetUpPr.fitToPage`, or `page_margins`. The quoted text states: "Also supported are evenHeader and evenFooter as well as firstHeader and firstFooter," but no code examples are provided for these variations.
|
||
|
||
## [FETCH #5] https://openpyxl.readthedocs.io/en/stable/formatting.html
|
||
**ASK:** Extract all code examples and API usage for ColorScaleRule, DataBarRule, IconSetRule, FormulaRule, CellIsRule, Rule with DifferentialStyle, and how to apply them with ws.conditional_formatting.add(). Include exact parameter names and any notes about stopIfTrue, formula referencing, and limitations.
|
||
|
||
# openpyxl Conditional Formatting API Reference
|
||
|
||
## ColorScaleRule
|
||
```python
|
||
from openpyxl.formatting.rule import ColorScaleRule
|
||
|
||
rule = ColorScaleRule(
|
||
start_type='percentile', start_value=10, start_color='FFAA0000',
|
||
mid_type='percentile', mid_value=50, mid_color='FF0000AA',
|
||
end_type='percentile', end_value=90, end_color='FF00AA00'
|
||
)
|
||
ws.conditional_formatting.add('A1:A10', rule)
|
||
```
|
||
Supports 2 or 3-color gradients. Type options: 'num', 'percent', 'max', 'min', 'formula', 'percentile'.
|
||
|
||
## DataBarRule
|
||
```python
|
||
from openpyxl.formatting.rule import DataBarRule
|
||
|
||
rule = DataBarRule(
|
||
start_type='percentile', start_value=10,
|
||
end_type='percentile', end_value='90',
|
||
color="FF638EC6", showValue="None",
|
||
minLength=None, maxLength=None
|
||
)
|
||
ws.conditional_formatting.add('A1:A10', rule)
|
||
```
|
||
Uses original specification; borders and directions require later extensions.
|
||
|
||
## IconSetRule
|
||
```python
|
||
from openpyxl.formatting.rule import IconSetRule
|
||
|
||
rule = IconSetRule('5Arrows', 'percent', [10, 20, 30, 40, 50],
|
||
showValue=None, percent=None, reverse=None)
|
||
ws.conditional_formatting.add('A1:A10', rule)
|
||
```
|
||
Available icon sets: '3Arrows', '3TrafficLights1', '4Arrows', '5Rating', etc.
|
||
|
||
## CellIsRule
|
||
```python
|
||
from openpyxl.formatting.rule import CellIsRule
|
||
from openpyxl.styles import PatternFill
|
||
|
||
redFill = PatternFill(start_color='EE1111', end_color='EE1111', fill_type='solid')
|
||
|
||
# Less than comparison
|
||
rule = CellIsRule(operator='lessThan', formula=['C$1'],
|
||
stopIfTrue=True, fill=redFill)
|
||
ws.conditional_formatting.add('C2:C10', rule)
|
||
|
||
# Between comparison
|
||
rule = CellIsRule(operator='between', formula=['1','5'],
|
||
stopIfTrue=True, fill=redFill)
|
||
ws.conditional_formatting.add('D2:D10', rule)
|
||
```
|
||
|
||
## FormulaRule
|
||
```python
|
||
from openpyxl.formatting.rule import FormulaRule
|
||
from openpyxl.styles import Font, Border, PatternFill
|
||
|
||
rule = FormulaRule(formula=['ISBLANK(E1)'], stopIfTrue=True, fill=redFill)
|
||
ws.conditional_formatting.add('E1:E10', rule)
|
||
|
||
# With styling
|
||
rule = FormulaRule(formula=['E1=0'], font=Font(),
|
||
border=Border(), fill=redFill)
|
||
ws.conditional_formatting.add('E1:E10', rule)
|
||
```
|
||
|
||
## Rule with DifferentialStyle
|
||
```python
|
||
from openpyxl.formatting.rule import Rule
|
||
from openpyxl.styles.differential import DifferentialStyle
|
||
from openpyxl.styles import Font, PatternFill
|
||
|
||
dxf = DifferentialStyle(
|
||
font=Font(bold=True),
|
||
fill=PatternFill(start_color='EE1111', end_color='EE1111')
|
||
)
|
||
rule = Rule(type='cellIs', dxf=dxf, formula=["10"])
|
||
|
||
# For text highlighting
|
||
red_text = Font(color="9C0006")
|
||
red_fill = PatternFill(bgColor="FFC7CE")
|
||
dxf = DifferentialStyle(font=red_text, fill=red_fill)
|
||
rule = Rule(type="containsText", operator="containsText",
|
||
text="highlight", dxf=dxf)
|
||
rule.formula = ['NOT(ISERROR(SEARCH("highlight",A1)))']
|
||
ws.conditional_formatting.add('A1:F40', rule)
|
||
```
|
||
|
||
## Formatting Entire Rows
|
||
```python
|
||
dxf = DifferentialStyle(fill=PatternFill(bgColor="FFC7CE"))
|
||
rule = Rule(type="expression", dxf=dxf, stopIfTrue=True)
|
||
rule.formula = ['$A2="Microsoft"'] # Absolute column, relative row
|
||
ws.conditional_formatting.add("A1:C10", rule)
|
||
```
|
||
|
||
**Key Notes:**
|
||
- The `stopIfTrue` parameter halts rule evaluation when matched
|
||
- Formulas require absolute column references (`$A`) but relative row numbers for multi-row ranges
|
||
- "The syntax for the different rules varies so much that it is not possible for openpyxl to know whether a rule makes sense"
|
||
- Rules can be adjusted post-addition to the conditional format collection
|
||
|
||
## [FETCH #6] https://openpyxl.readthedocs.io/en/stable/worksheet_properties.html
|
||
**ASK:** Extract all code examples about worksheet properties: tabColor, sheet_properties, outlinePr, pageSetUpPr fitToPage, sheet_view settings, zoomScale, showGridLines. Verbatim.
|
||
|
||
# Worksheet Properties Code Examples
|
||
|
||
Here are the code examples from the documentation:
|
||
|
||
## Tab Color and Sheet Properties
|
||
```python
|
||
>>> from openpyxl.workbook import Workbook
|
||
>>> from openpyxl.worksheet.properties import WorksheetProperties, PageSetupProperties
|
||
>>>
|
||
>>> wb = Workbook()
|
||
>>> ws = wb.active
|
||
>>>
|
||
>>> wsprops = ws.sheet_properties
|
||
>>> wsprops.tabColor = "1072BA"
|
||
>>> wsprops.filterMode = False
|
||
>>> wsprops.pageSetUpPr = PageSetupProperties(fitToPage=True, autoPageBreaks=False)
|
||
>>> wsprops.outlinePr.summaryBelow = False
|
||
>>> wsprops.outlinePr.applyStyles = True
|
||
>>> wsprops.pageSetUpPr.autoPageBreaks = True
|
||
```
|
||
|
||
## Sheet View Settings
|
||
```python
|
||
>>> from openpyxl.workbook import Workbook
|
||
>>>
|
||
>>> wb = Workbook()
|
||
>>> ws = wb.active
|
||
>>>
|
||
>>> ws.sheet_view.zoomScale = 85 # Sets 85% zoom
|
||
>>> ws.sheet_view.showFormulas = True
|
||
>>> ws.sheet_view.tabSelected = True
|
||
```
|
||
|
||
## Outline/Fold Example
|
||
```python
|
||
>>> import openpyxl
|
||
>>> wb = openpyxl.Workbook()
|
||
>>> ws = wb.create_sheet()
|
||
>>> ws.column_dimensions.group('A','D', hidden=True)
|
||
>>> ws.row_dimensions.group(1,10, hidden=True)
|
||
>>> wb.save('group.xlsx')
|
||
```
|
||
|
||
## [FETCH #7] https://openpyxl.readthedocs.io/en/stable/tutorial.html
|
||
**ASK:** Find the exact warning about images and charts being lost when loading and saving existing files, and any notes on load_workbook keep_vba, data_only, and saving. Quote verbatim.
|
||
|
||
# Key Warnings and Notes from openpyxl Documentation
|
||
|
||
**On images and charts being lost:**
|
||
"openpyxl does currently not read all possible items in an Excel file so shapes will be lost from existing files if they are opened and saved with the same name."
|
||
|
||
**On keep_vba parameter:**
|
||
"keep_vba controls whether any Visual Basic elements are preserved or not (default). If they are preserved they are still not editable."
|
||
|
||
**On data_only parameter:**
|
||
"data_only controls whether cells with formulae have either the formula (default) or the value stored the last time Excel read the sheet."
|
||
|
||
**On saving with proper extensions:**
|
||
The documentation warns that using incorrect file extensions (like saving `.xlsx` files as `.xlsm`) or failing to preserve VBA with `keep_vba=True` will prevent Microsoft Excel from opening the resulting document.
|
||
|
||
## [FETCH #8] https://openpyxl.readthedocs.io/en/stable/optimized.html
|
||
**ASK:** Extract everything about write_only mode: Workbook(write_only=True), create_sheet, append, WriteOnlyCell for styling, limitations (no ws.cell access, only append, must save once, freeze panes/ column dimensions rules), and read_only mode. Verbatim code.
|
||
|
||
# Optimised Modes in openpyxl
|
||
|
||
## Write-Only Mode
|
||
|
||
**Basic Usage:**
|
||
```python
|
||
from openpyxl import Workbook
|
||
wb = Workbook(write_only=True)
|
||
ws = wb.create_sheet()
|
||
|
||
for irow in range(100):
|
||
ws.append(['%d' % i for i in range(200)])
|
||
wb.save('new_big_file.xlsx')
|
||
```
|
||
|
||
**With Styling:**
|
||
```python
|
||
from openpyxl import Workbook
|
||
from openpyxl.cell import WriteOnlyCell
|
||
from openpyxl.comments import Comment
|
||
from openpyxl.styles import Font
|
||
|
||
wb = Workbook(write_only=True)
|
||
ws = wb.create_sheet()
|
||
cell = WriteOnlyCell(ws, value="hello world")
|
||
cell.font = Font(name='Courier', size=36)
|
||
cell.comment = Comment(text="A comment", author="Author's Name")
|
||
ws.append([cell, 3.14, None])
|
||
wb.save('write_only_file.xlsx')
|
||
```
|
||
|
||
**Key Limitations:**
|
||
- "Unlike a normal workbook, a newly-created write-only workbook does not contain any worksheets; a worksheet must be specifically created with the `create_sheet()` method."
|
||
- Rows can only be added via `append()`; arbitrary cell access via `cell()` or `iter_rows()` is prohibited
|
||
- Handles unlimited data while maintaining minimal memory usage
|
||
- "A write-only workbook can only be saved once"
|
||
- Structural elements (freeze panes, column dimensions) must be configured before adding cells
|
||
|
||
## Read-Only Mode
|
||
|
||
**Basic Usage:**
|
||
```python
|
||
from openpyxl import load_workbook
|
||
wb = load_workbook(filename='large_file.xlsx', read_only=True)
|
||
ws = wb['big_data']
|
||
|
||
for row in ws.rows:
|
||
for cell in row:
|
||
print(cell.value)
|
||
wb.close()
|
||
```
|
||
|
||
**Key Features:**
|
||
- "The workbook must be explicitly closed with the `close()` method"
|
||
- Uses lazy loading for constant memory consumption
|
||
- Returns `ReadOnlyCell` objects rather than standard `Cell` objects
|
||
|
||
## [FETCH #9] https://openpyxl.readthedocs.io/en/stable/worksheet_tables.html
|
||
**ASK:** Extract all code examples for creating Excel worksheet tables in openpyxl: Table, TableStyleInfo, ws.add_table, displayName rules, ref, showRowStripes, table name uniqueness, notes about autofilter, headers must be strings, and structured references. Verbatim.
|
||
|
||
# Openpyxl Worksheet Tables: Code Examples and Rules
|
||
|
||
## Creating a Table
|
||
|
||
```python
|
||
from openpyxl import Workbook
|
||
from openpyxl.worksheet.table import Table, TableStyleInfo
|
||
|
||
wb = Workbook()
|
||
ws = wb.active
|
||
|
||
data = [
|
||
['Apples', 10000, 5000, 8000, 6000],
|
||
['Pears', 2000, 3000, 4000, 5000],
|
||
['Bananas', 6000, 6000, 6500, 6000],
|
||
['Oranges', 500, 300, 200, 700],
|
||
]
|
||
|
||
ws.append(["Fruit", "2011", "2012", "2013", "2014"])
|
||
for row in data:
|
||
ws.append(row)
|
||
|
||
tab = Table(displayName="Table1", ref="A1:E5")
|
||
|
||
style = TableStyleInfo(name="TableStyleMedium9", showFirstColumn=False,
|
||
showLastColumn=False, showRowStripes=True, showColumnStripes=True)
|
||
tab.tableStyleInfo = style
|
||
|
||
ws.add_table(tab)
|
||
wb.save("table.xlsx")
|
||
```
|
||
|
||
## Key Rules
|
||
|
||
**Table Names:** Must be unique within a workbook. Use `ws.add_table()` to ensure uniqueness.
|
||
|
||
**Headers & Strings:** "column headings must always contain strings" and headers come from the first row by default.
|
||
|
||
**Filters:** "Filters will be added automatically to tables that contain header rows. It is **not** possible to create tables with header rows without filters."
|
||
|
||
**Write-Only Mode:** Manual column heading initialization required; values must match corresponding cells to maintain file validity.
|
||
|
||
**Styling:** TableStyleInfo manages appearance through stripe options and color schemes.
|
||
|
||
## [FETCH #10] https://openpyxl.readthedocs.io/en/stable/charts/introduction.html
|
||
**ASK:** Extract the basic chart creation example: BarChart, LineChart, PieChart/DoughnutChart, Reference, add_data, set_categories, ws.add_chart with anchor, chart.width/height, title, style, data labels (DataLabelList). Include the list of chart types supported. Verbatim code.
|
||
|
||
# OpenPyXL Charts Overview
|
||
|
||
## Supported Chart Types
|
||
|
||
The documentation lists these available chart types:
|
||
- Area Charts (2D and 3D)
|
||
- Bar and Column Charts
|
||
- Bubble Charts
|
||
- Line Charts
|
||
- Scatter Charts
|
||
- Pie Charts (including 3D and Gradient variants)
|
||
- Doughnut Charts
|
||
- Radar Charts
|
||
- Stock Charts
|
||
- Surface Charts
|
||
|
||
## Basic Chart Creation Example
|
||
|
||
The documentation provides this code sample:
|
||
|
||
```python
|
||
from openpyxl import Workbook
|
||
wb = Workbook()
|
||
ws = wb.active
|
||
for i in range(10):
|
||
ws.append([i])
|
||
|
||
from openpyxl.chart import BarChart, Reference, Series
|
||
values = Reference(ws, min_col=1, min_row=1, max_col=1, max_row=10)
|
||
chart = BarChart()
|
||
chart.add_data(values)
|
||
ws.add_chart(chart, "E15")
|
||
wb.save("SampleChart.xlsx")
|
||
```
|
||
|
||
## Key Points
|
||
|
||
The documentation states that "charts are composed of at least one series of one or more data points." By default, a chart's top-left corner anchors to cell E15 with dimensions of approximately "15 x 7.5 cm (approximately 5 columns by 14 rows)." Users can customize this through anchor, width, and height properties.
|
||
|
||
**Note:** The provided content doesn't include detailed examples for LineChart, PieChart/DoughnutChart configuration, set_categories, chart styling, DataLabelList, or width/height modifications.
|
||
|
||
## [FETCH #11] https://xlsxwriter.readthedocs.io/working_with_sparklines.html
|
||
**ASK:** Extract the full add_sparkline API: all option keys (range, type, markers, style, high_point, low_point, negative_points, first_point, last_point, series_color, axis, reverse, weight, date_axis, min, max, empty_cells, show_hidden, location for multiple sparklines), the basic and advanced examples verbatim, and any note that sparklines are xlsxwriter-only / not supported in openpyxl / grouped spark
|
||
…[truncated 6 chars]
|
||
|
||
# XlsxWriter add_sparkline() API
|
||
|
||
## Complete Option Keys
|
||
|
||
The `add_sparkline()` method accepts these parameters in a dictionary:
|
||
|
||
**Required:**
|
||
- `range` - Cell data range the sparkline plots
|
||
|
||
**Main Parameters:**
|
||
- `type` - Sparkline type (line, column, win_loss)
|
||
- `style` - Built-in style number (1-36)
|
||
- `markers` - Show markers on line sparklines
|
||
- `negative_points` - Highlight negative values
|
||
- `axis` - Display horizontal axis
|
||
- `reverse` - Plot right-to-left
|
||
|
||
**Point Highlighting:**
|
||
- `high_point` - Highlight highest value
|
||
- `low_point` - Highlight lowest value
|
||
- `first_point` - Highlight first value
|
||
- `last_point` - Highlight last value
|
||
|
||
**Scaling & Data:**
|
||
- `max` / `min` - Set vertical axis bounds
|
||
- `empty_cells` - Handle empty cells (gaps, zero, connect)
|
||
- `show_hidden` - Plot hidden rows/columns
|
||
- `date_axis` - Alternative date axis range
|
||
- `weight` - Line thickness (0.25, 0.5, 0.75, 1, 1.25, 2.25, 3, 4.25, 6)
|
||
|
||
**Colors:**
|
||
- `series_color` - Main color (#rrggbb format)
|
||
- `negative_color` - Negative value color
|
||
- `markers_color` - Marker color
|
||
- `first_color` / `last_color` - Endpoint colors
|
||
- `high_color` / `low_color` - Extrema colors
|
||
|
||
**Grouped Sparklines:**
|
||
- `location` - Array of cell locations for multiple sparklines
|
||
|
||
## Key Notes
|
||
|
||
"Sparklines are a feature of Excel 2010+ only. You can write them to an XLSX file that can be read by Excel 2007 but they won't be displayed."
|
||
|
||
For grouped sparklines, pass arrays to both `location` and `range` parameters to apply changes across multiple contiguous cells simultaneously.
|
||
|
||
## [FETCH #12] https://xlsxwriter.readthedocs.io/working_with_tables.html
|
||
**ASK:** Extract the add_table API: parameters (data, autofilter, header_row, banded_columns, banded_rows, first_column, last_column, style, total_row, columns with header, header_format, formula, total_string, total_function, total_value, format, name). Include example code with structured reference formulas and total_row. Verbatim.
|
||
|
||
# XlsxWriter add_table() API Reference
|
||
|
||
## Method Signature
|
||
```python
|
||
worksheet.add_table('B3:F7', {options})
|
||
```
|
||
|
||
## Parameters
|
||
|
||
| Parameter | Description |
|
||
|-----------|-------------|
|
||
| `data` | List of lists containing row data |
|
||
| `autofilter` | Toggle filter dropdowns in header (default: True) |
|
||
| `header_row` | Display header row (default: True) |
|
||
| `banded_rows` | Alternating row colors (default: True) |
|
||
| `banded_columns` | Alternating column colors (default: False) |
|
||
| `first_column` | Highlight first column (default: False) |
|
||
| `last_column` | Highlight last column (default: False) |
|
||
| `style` | Table style name; default is 'Table Style Medium 9' |
|
||
| `total_row` | Enable totals row (default: False) |
|
||
| `name` | Custom table name (defaults to Table1, Table2, etc.) |
|
||
| `columns` | List of column configuration dicts |
|
||
|
||
## Column Sub-Properties
|
||
- `header`: Column header text
|
||
- `header_format`: Format object for header
|
||
- `formula`: Column formula using structured references
|
||
- `total_string`: Label for totals row
|
||
- `total_function`: SUBTOTAL function (sum, average, count, max, min, etc.)
|
||
- `total_value`: Calculated total value
|
||
- `format`: Format object for column data
|
||
|
||
## Example with Formulas and Total Row
|
||
|
||
```python
|
||
options = {'data': data,
|
||
'total_row': 1,
|
||
'columns': [{'header': 'Product', 'total_string': 'Totals'},
|
||
{'header': 'Quarter 1', 'total_function': 'sum'},
|
||
{'header': 'Quarter 2', 'total_function': 'sum'},
|
||
{'header': 'Quarter 3', 'total_function': 'sum'},
|
||
{'header': 'Quarter 4', 'total_function': 'sum'},
|
||
{'header': 'Year',
|
||
'formula': '=SUM(Table10[@[Quarter 1]:[Quarter 4]])',
|
||
'total_function': 'sum'}]}
|
||
|
||
worksheet.add_table('B3:G8', options)
|
||
```
|
||
|
||
Structured references use `@` (Excel 2010 style) or `[#This Row]` (Excel 2007 style) syntax for row references within table formulas.
|
||
|
||
## [FETCH #13] https://xlsxwriter.readthedocs.io/working_with_conditional_formats.html
|
||
**ASK:** Extract the conditional_format API: all type values (cell, date, text, time_period, average, duplicate, unique, top, bottom, blanks, no_blanks, errors, no_errors, formula, 2_color_scale, 3_color_scale, data_bar, icon_set), the option keys for each (criteria, value, minimum, maximum, format, min_color, max_color, mid_color, bar_color, bar_solid, bar_negative_color, icon_style, icons, reverse_icons,
|
||
…[truncated 117 chars]
|
||
|
||
# XlsxWriter conditional_format() API Reference
|
||
|
||
## Type Values
|
||
|
||
The `conditional_format()` method supports these type values:
|
||
|
||
- `cell` - Format based on cell criteria
|
||
- `date` - Format based on date criteria
|
||
- `time_period` - Excel's "Dates Occurring" style format
|
||
- `text` - String matching format
|
||
- `average` - Average-based format
|
||
- `duplicate` - Highlight duplicate cells
|
||
- `unique` - Highlight unique cells
|
||
- `top` - Top n values by number or percentage
|
||
- `bottom` - Bottom n values by number or percentage
|
||
- `blanks` - Highlight empty cells
|
||
- `no_blanks` - Highlight non-empty cells
|
||
- `errors` - Highlight error cells
|
||
- `no_errors` - Highlight non-error cells
|
||
- `formula` - User-defined formula format
|
||
- `2_color_scale` - Two-color gradient scale
|
||
- `3_color_scale` - Three-color gradient scale
|
||
- `data_bar` - Data bar visualization
|
||
- `icon_set` - Icon set indicators
|
||
|
||
## Common Option Keys
|
||
|
||
- `criteria` - Comparison operator or condition type
|
||
- `value` - Comparison value
|
||
- `minimum` / `maximum` - Range boundaries
|
||
- `format` - Format object to apply
|
||
- `min_color` / `max_color` / `mid_color` - Scale colors
|
||
- `bar_color` - Data bar fill color
|
||
- `bar_solid` - Solid (non-gradient) bars
|
||
- `bar_negative_color` - Negative value color
|
||
- `icon_style` - Icon set style
|
||
- `icons` - Array of icon specifications
|
||
- `reverse_icons` - Reverse icon order
|
||
- `icons_only` - Display icons without values
|
||
- `stop_if_true` - Halt evaluation of subsequent rules
|
||
- `multi_range` - Apply to non-contiguous ranges
|
||
|
||
## Example: Formula-Based Highlighting
|
||
|
||
```python
|
||
worksheet.conditional_format('A1:A4', {'type': 'formula',
|
||
'criteria': '=$A$1>5',
|
||
'format': format1})
|
||
```
|
||
|
||
## Example: Duplicate Detection
|
||
|
||
```python
|
||
worksheet.conditional_format('A1:A4', {'type': 'duplicate',
|
||
'format': format1})
|
||
```
|
||
|
||
## [FETCH #14] https://xlsxwriter.readthedocs.io/example_dynamic_arrays.html
|
||
**ASK:** Extract the full example code for dynamic array formulas in xlsxwriter: write_dynamic_array_formula, FILTER, UNIQUE, SORT, XLOOKUP, LET, SEQUENCE examples; how write_formula handles future functions automatically and the use_future_functions workbook option. Verbatim code.
|
||
|
||
# Dynamic Array Formulas in XlsxWriter
|
||
|
||
The provided code demonstrates dynamic array functionality in XlsxWriter. Here's what's covered:
|
||
|
||
## Key Functions Demonstrated
|
||
|
||
**FILTER**: `"=FILTER(A1:D17,C1:C17=K2)"` - filters data based on criteria
|
||
|
||
**UNIQUE**: `"=UNIQUE(B2:B17)"` - extracts unique values from a range
|
||
|
||
**SORT**: `"=SORT(B2:B17)"` - sorts array values; also `"=SORT(FILTER(C2:D17,D2:D17>5000,""),2,1)"` combining functions
|
||
|
||
**SORTBY**: `"=SORTBY(A2:B9,B2:B9)"` - sorts one range by another
|
||
|
||
**XLOOKUP**: `"=XLOOKUP(E1,A2:A9,C2:C9)"` - advanced lookup function
|
||
|
||
**XMATCH**: `"=XMATCH(C2,A2:A6)"` - returns position of matched value
|
||
|
||
**SEQUENCE**: `"=SEQUENCE(4,5)"` - generates sequential number arrays
|
||
|
||
**RANDARRAY**: `"=RANDARRAY(5,3,1,100, TRUE)"` - creates random number arrays
|
||
|
||
**ANCHORARRAY**: `"=ANCHORARRAY(F2)"` - references spill ranges
|
||
|
||
## Dynamic Array Method
|
||
|
||
The code uses `write_dynamic_array_formula("B1:B3", "=LEN(A1:A3)")` to apply formulas across ranges, demonstrating how older functions gain dynamic array capabilities in Excel 365.
|
||
|
||
Note: The documentation mentions `write_dynamic_array_formula()` method but doesn't detail `use_future_functions` workbook option in this excerpt.
|
||
|
||
## [FETCH #15] https://xlsxwriter.readthedocs.io/example_chart_data_labels.html
|
||
**ASK:** Extract the example code showing add_series with data_labels options (value, category, series_name, position, num_format, font, custom, percentage, leader_lines), and insert_chart with x_offset/y_offset/x_scale/y_scale, set_size. Verbatim code.
|
||
|
||
# XlsxWriter Chart Data Labels and Insert Examples
|
||
|
||
Based on the provided documentation, here are the verbatim code examples:
|
||
|
||
## add_series with data_labels options:
|
||
|
||
```python
|
||
chart1.add_series(
|
||
{
|
||
"categories": "=Sheet1!$A$2:$A$7",
|
||
"values": "=Sheet1!$B$2:$B$7",
|
||
"data_labels": {"value": True},
|
||
}
|
||
)
|
||
```
|
||
|
||
```python
|
||
chart2.add_series(
|
||
{
|
||
"categories": "=Sheet1!$A$2:$A$7",
|
||
"values": "=Sheet1!$B$2:$B$7",
|
||
"data_labels": {"value": True, "category": True},
|
||
}
|
||
)
|
||
```
|
||
|
||
```python
|
||
chart3.add_series(
|
||
{
|
||
"categories": "=Sheet1!$A$2:$A$7",
|
||
"values": "=Sheet1!$B$2:$B$7",
|
||
"data_labels": {
|
||
"value": True,
|
||
"font": {"bold": True, "color": "red", "rotation": -30},
|
||
},
|
||
}
|
||
)
|
||
```
|
||
|
||
## insert_chart with offsets:
|
||
|
||
```python
|
||
worksheet.insert_chart("D2", chart1, {"x_offset": 25, "y_offset": 10})
|
||
```
|
||
|
||
**Note:** The provided content does not include examples demonstrating `series_name`, `position`, `num_format`, `percentage`, `leader_lines`, `set_size`, `x_scale`, or `y_scale` parameters.
|
||
|
||
## [FETCH #16] https://pandas.pydata.org/docs/reference/api/pandas.ExcelWriter.html
|
||
**ASK:** Extract the full signature of pandas.ExcelWriter, the description of mode ('w','a'), if_sheet_exists ('error','new','replace','overlay') with exact semantics and version added, engine_kwargs, date_format/datetime_format, and the code examples for mode='a' with openpyxl including overlay with startrow/startcol. Note that append mode requires openpyxl (xlsxwriter cannot append). Verbatim.
|
||
|
||
# pandas.ExcelWriter Full Signature and Documentation
|
||
|
||
## Full Signature
|
||
```python
|
||
class pandas.ExcelWriter(
|
||
path,
|
||
engine=None,
|
||
date_format=None,
|
||
datetime_format=None,
|
||
mode='w',
|
||
storage_options=None,
|
||
if_sheet_exists=None,
|
||
engine_kwargs=None
|
||
)
|
||
```
|
||
|
||
## mode Parameter
|
||
**mode** : {'w', 'a'}, default 'w'
|
||
|
||
File mode to use (write or append). Append does not work with fsspec URLs.
|
||
|
||
## if_sheet_exists Parameter
|
||
**if_sheet_exists** : {'error', 'new', 'replace', 'overlay'}, default 'error'
|
||
|
||
How to behave when trying to write to a sheet that already exists (append mode only).
|
||
|
||
- **error**: raise a ValueError.
|
||
- **new**: Create a new sheet, with a name determined by the engine.
|
||
- **replace**: Delete the contents of the sheet before writing to it.
|
||
- **overlay**: Write contents to the existing sheet without first removing, but possibly over top of, the existing contents.
|
||
|
||
## date_format and datetime_format Parameters
|
||
**date_format** : str, default None
|
||
Format string for dates written into Excel files (e.g. 'YYYY-MM-DD').
|
||
|
||
**datetime_format** : str, default None
|
||
Format string for datetime objects written into Excel files. (e.g. 'YYYY-MM-DD HH:MM:SS').
|
||
|
||
## engine_kwargs Parameter
|
||
**engine_kwargs** : dict, optional
|
||
|
||
Keyword arguments to be passed into the engine. These will be passed to the following functions of the respective engines:
|
||
|
||
- xlsxwriter: `xlsxwriter.Workbook(file, **engine_kwargs)`
|
||
- openpyxl (write mode): `openpyxl.Workbook(**engine_kwargs)`
|
||
- openpyxl (append mode): `openpyxl.load_workbook(file, **engine_kwargs)`
|
||
- odf: `odf.opendocument.OpenDocumentSpreadsheet(**engine_kwargs)`
|
||
|
||
## Code Examples for Append Mode with openpyxl
|
||
|
||
### Basic Append:
|
||
```python
|
||
with pd.ExcelWriter("path_to_file.xlsx", mode="a", engine="openpyxl") as writer:
|
||
df.to_excel(writer, sheet_name="Sheet3")
|
||
```
|
||
|
||
### Append with Replace:
|
||
```python
|
||
with pd.ExcelWriter(
|
||
"path_to_file.xlsx",
|
||
mode="a",
|
||
engine="openpyxl",
|
||
if_sheet_exists="replace",
|
||
) as writer:
|
||
df.to_excel(writer, sheet_name="Sheet1")
|
||
```
|
||
|
||
### Append with Overlay (Multiple DataFrames):
|
||
```python
|
||
with pd.ExcelWriter(
|
||
"path_to_file.xlsx",
|
||
mode="a",
|
||
engine="openpyxl",
|
||
if_sheet_exists="overlay",
|
||
) as writer:
|
||
df1.to_excel(writer, sheet_name="Sheet1")
|
||
df2.to_excel(writer, sheet_name="Sheet1", startcol=3)
|
||
```
|
||
|
||
**Note:** The documentation does not include `startrow` in the overlay example; only `startcol=3` is shown.
|
||
|
||
## [FETCH #17] https://github.com/anthropics/skills/blob/main/skills/xlsx/SKILL.md
|
||
**ASK:** Extract everything about formula recalculation: the recalc.py script usage (python recalc.py file.xlsx [timeout]), what it does (LibreOffice headless via soffice --headless --convert-to xlsx, or macro), how it checks for errors like #REF! #NAME?, and any guidance about openpyxl not computing formulas, and best practices for formatting Excel reports (headers, number formats, column widths, freeze p
|
||
…[truncated 31 chars]
|
||
|
||
# Formula Recalculation Guide
|
||
|
||
## recalc.py Script Usage
|
||
|
||
```bash
|
||
python scripts/recalc.py output.xlsx [timeout_seconds] # default 30
|
||
```
|
||
|
||
## What recalc.py Does
|
||
|
||
**LibreOffice computes every formula**, the file is **rewritten in place**, and returns JSON output with:
|
||
- `status` (`success` | `errors_found`)
|
||
- `total_formulas`
|
||
- `total_errors`
|
||
- `error_summary` — names up to 100 cells per error type; `locations_truncated` indicates how many were withheld
|
||
|
||
**Critical**: JSON with an `error` key instead of a `status` means nothing was recalculated, and only that case exits non-zero. `errors_found` exits 0, so **never treat a clean exit as a clean workbook**.
|
||
|
||
## Error Detection
|
||
|
||
recalc.py identifies formula errors like:
|
||
- `#REF!` (broken references)
|
||
- `#NAME?` (undefined functions or unsupported syntax)
|
||
- `#VALUE!` (type mismatches)
|
||
- Other spreadsheet error codes
|
||
|
||
**A green recalc proves your formulas _evaluate_, not that they are _right_.** An off-by-one range or reference to the wrong row yields a clean, error-free file with wrong numbers. Write 2–3 formulas first and check they pull the expected values before building out a grid.
|
||
|
||
## Why openpyxl Requires Recalculation
|
||
|
||
openpyxl writes formulas as strings with **no cached values**. Until you recalculate, every formula cell reads back as `None` to anything reading cached values — `pandas`, `load_workbook(data_only=True)`, and most previewers.
|
||
|
||
## Mandatory Usage
|
||
|
||
**Recalculate is mandatory whenever the file contains formulas.** This is a requirement for every output.
|
||
|
||
## External Links Caveat
|
||
|
||
A workbook that links to another file **loses those links** if you re-save it with openpyxl and then recalculate. Such a formula reads `='[1]Returns Analysis'!$B$2` — the `[1]` is an index into an external-reference list naming a separate file on disk. That file is rarely present, so LibreOffice fails to resolve the reference, writes `#NAME?`, and deletes every link. `recalc.py` refuses to run in that state — use `--force` to override and accept the loss, or copy those cells' values out of the original before saving over them.
|
||
|
||
## [FETCH #18] https://xlsxwriter.readthedocs.io/working_with_formulas.html
|
||
**ASK:** Extract: the explanation that xlsxwriter doesn't calculate formulas and the result is 0 until Excel recalculates; the 'value' parameter in write_formula for precomputed result; the _xlfn. prefix / future functions list (XLOOKUP, FILTER, UNIQUE, etc.), use_future_functions workbook option; dynamic array formulas; the note on LibreOffice not recalculating on load and 'Recalculation on load' settings
|
||
…[truncated 68 chars]
|
||
|
||
# Key XlsxWriter Formula Handling Points
|
||
|
||
## Formula Calculation Behavior
|
||
|
||
XlsxWriter doesn't compute formula results; instead, it stores `0` as the initial value and sets a flag instructing Excel to recalculate upon opening. This approach works with most spreadsheet applications, but applications lacking calculation capabilities (Excel Viewer, PDF converters, mobile apps) will only display the zero placeholder.
|
||
|
||
## Specifying Precomputed Results
|
||
|
||
You can provide a calculated result using the optional `value` parameter in `write_formula()`:
|
||
|
||
```python
|
||
worksheet.write_formula('A1', '=2+2', num_format, 4)
|
||
```
|
||
|
||
This parameter accepts numbers, strings, booleans, or Excel error codes like `#DIV/0!`, `#N/A`, `#NAME?`, etc.
|
||
|
||
## Formula Syntax Requirements
|
||
|
||
Formulas must follow US English conventions:
|
||
- Use function names in English (e.g., `SUM`, not `SOMME`)
|
||
- Employ commas as separators: `=SUM(1, 2, 3)` ✓ rather than `=SUM(1; 2; 3)` ✗
|
||
|
||
## Future Functions & Dynamic Arrays
|
||
|
||
Excel 2010+ introduced "future functions" requiring the `_xlfn.` prefix, including dynamic array functions like `FILTER`, `UNIQUE`, `XLOOKUP`, and `LAMBDA`. These include:
|
||
|
||
- Modern functions: `STDEV.S`, `CONFIDENCE.NORM`, `TEXTJOIN`
|
||
- Dynamic array functions: `FILTER`, `UNIQUE`, `XLOOKUP`, `SORT`, `SEQUENCE`
|
||
|
||
Enable automatic prefix handling via:
|
||
```python
|
||
workbook = Workbook('file.xlsx', {'use_future_functions': True})
|
||
```
|
||
|
||
Otherwise, manually prefix functions: `=_xlfn.STDEV.S(B1:B10)`
|
||
|
||
## [FETCH #19] https://github.com/dakixr/xpyxl
|
||
**ASK:** Summarize what xpyxl is, its features (declarative styled reports, xlsxwriter+openpyxl backends), a code example, stars if visible, latest activity/commit date, license, and Python version requirement.
|
||
|
||
# xpyxl Summary
|
||
|
||
**What It Is:**
|
||
xpyxl is a Python library for generating styled Excel reports using declarative syntax rather than manual cell coordinates.
|
||
|
||
**Core Features:**
|
||
- Positionless composition with `row`, `col`, `cell`, `table`, `vstack`, and `hstack` primitives
|
||
- Tailwind-inspired utility styling classes for typography, colors, alignment, and number formats
|
||
- Three rendering engines: hybrid (default), openpyxl, and xlsxwriter
|
||
- Sheet importing capabilities (hybrid and openpyxl engines)
|
||
- PDF/PNG export via Chromium or ReportLab
|
||
|
||
**Code Example:**
|
||
```python
|
||
import xpyxl as x
|
||
|
||
report = (
|
||
x.workbook()[
|
||
x.sheet("Summary")[
|
||
x.row(style=[x.text_2xl, x.bold, x.text_blue])["Q3 Sales Overview"],
|
||
x.row(style=[x.text_sm, x.text_gray])["Region", "Units", "Price"],
|
||
x.row(style=[x.bg_primary, x.text_white, x.bold])["EMEA", 1200, 19.0],
|
||
]
|
||
]
|
||
)
|
||
report.save("report.xlsx")
|
||
```
|
||
|
||
**Repository Stats:**
|
||
- 3 stars
|
||
- 57 commits on main branch
|
||
- No open issues or pull requests
|
||
|
||
**Technical Details:**
|
||
- Full type hints and pure Python stack
|
||
- Deterministic rendering suitable for CI diffing
|
||
- Supports scalars, formulas, and datetime values
|
||
- Python version: .python-version file present (specific version not visible in content)
|
||
|
||
No license information or latest commit date explicitly visible in the provided content.
|
||
|
||
## [FETCH #20] https://wikidocs.net/302402
|
||
**ASK:** 이 페이지의 내용을 요약해라: OpenPyXL로 자동 보고서 만들기 챕터의 구성, 헤더 스타일, 조건부 서식, 차트, 하이퍼링크, 열 너비 등 어떤 기법을 다루는지, 코드 예시 핵심 부분.
|
||
|
||
The server returned HTTP 403 Forbidden.
|
||
|
||
The response body was not retrieved. If this URL requires authentication, use an authenticated tool (e.g. `gh` for GitHub, or an MCP-provided fetch tool) instead of WebFetch.
|
||
|
||
## [FETCH #21] https://qiita.com/Nomisugi/items/f451ad9f67d3e419c73b
|
||
**ASK:** Extract the approach and code for auto-fitting column width in openpyxl with Japanese/East Asian characters using unicodedata.east_asian_width and font size adjustments. Include the key code verbatim.
|
||
|
||
# Auto-fitting Column Width in Openpyxl with East Asian Characters
|
||
|
||
## Approach
|
||
|
||
The solution addresses three key considerations:
|
||
|
||
1. **East Asian character width differentiation** – Full-width and half-width characters require different multipliers
|
||
2. **Font size compensation** – Column width adjusts based on cell font size
|
||
3. **Pixel-based calculation** – Uses a font-dependent coefficient to account for actual rendering
|
||
|
||
## Key Code
|
||
|
||
```python
|
||
from unicodedata import east_asian_width
|
||
|
||
width_dict = {
|
||
'F': 2, # Fullwidth
|
||
'H': 1, # Halfwidth
|
||
'W': 2, # Wide
|
||
'Na': 1, # Narrow
|
||
'A': 2, # Ambiguous
|
||
'N': 1 # Neutral
|
||
}
|
||
|
||
Font_depend = 1.2
|
||
|
||
def sheet_adjusted_width(ws):
|
||
for col in ws.columns:
|
||
max_length = 1
|
||
max_diameter = 1
|
||
column = col[1].column_letter
|
||
for cell in col:
|
||
diameter = (cell.font.size * Font_depend) / 10
|
||
if diameter > max_diameter:
|
||
max_diameter = diameter
|
||
if cell.value:
|
||
chars = [char for char in str(cell.value)]
|
||
east_asian_width_list = [east_asian_width(char) for char in chars]
|
||
width_list = [width_dict[w] for w in east_asian_width_list]
|
||
if sum(width_list) > max_length:
|
||
max_length = sum(width_list)
|
||
ws.column_dimensions[column].width = max_length * max_diameter + 1.2
|
||
```
|
||
|
||
The `east_asian_width()` function classifies each character, allowing proper width calculation that respects character rendering width rather than simple character counts.
|
||
|
||
## [FETCH #22] https://xlsxwriter.readthedocs.io/worksheet.html
|
||
**ASK:** Extract the API for: worksheet.write_url with 'internal:Sheet1!A1' links (including sheet names with spaces quoted), worksheet.autofit() (including note about how it estimates and limitations), freeze_panes, autofilter, set_column with width/format/options hidden and level for grouping, set_row, set_landscape, fit_to_pages, repeat_rows, set_tab_color, hide_gridlines, set_zoom, print_area, set_pape
|
||
…[truncated 124 chars]
|
||
|
||
# XlsxWriter Worksheet API Reference
|
||
|
||
## worksheet.write_url() - Internal Links
|
||
|
||
**Signature:**
|
||
```python
|
||
write_url(row, col, url[, cell_format[, string[, tip]]])
|
||
```
|
||
|
||
**Internal Link Format:**
|
||
```python
|
||
# Link to current worksheet cell
|
||
worksheet.write_url('A1', 'internal:Sheet2!A1')
|
||
|
||
# Worksheet names with spaces require single quotes
|
||
worksheet.write_url('A3', "internal:'Sales Data'!A1")
|
||
|
||
# Link to cell range
|
||
worksheet.write_url('A2', 'internal:Sheet2!A1:B2')
|
||
```
|
||
|
||
---
|
||
|
||
## worksheet.autofit()
|
||
|
||
**Signature:**
|
||
```python
|
||
autofit([max_width])
|
||
```
|
||
|
||
**Description:** Simulates autofitting column widths based on the largest content in each column.
|
||
|
||
**Key Limitation:** The method estimates widths using Calibri 11 metrics and "doesn't take formatting of numbers or dates account."
|
||
|
||
**Performance Note:** For large worksheets, consider calling after ~100-200 rows to avoid performance penalties on non-visible data.
|
||
|
||
**Usage:**
|
||
```python
|
||
worksheet.autofit() # Default max width: 1790 pixels
|
||
worksheet.autofit(300) # Recommended limit for readability
|
||
```
|
||
|
||
---
|
||
|
||
## worksheet.freeze_panes()
|
||
|
||
**Signature:**
|
||
```python
|
||
freeze_panes(row, col[, top_row[, left_col]])
|
||
```
|
||
|
||
Freezes rows and columns at specified position.
|
||
|
||
---
|
||
|
||
## worksheet.autofilter()
|
||
|
||
**Signature:**
|
||
```python
|
||
autofilter(first_row, first_col, last_row, last_col)
|
||
```
|
||
|
||
Adds dropdown filter controls to a cell range.
|
||
|
||
---
|
||
|
||
## worksheet.set_column() - Grouping
|
||
|
||
**Signature:**
|
||
```python
|
||
set_column(first_col, last_col, width, cell_format, options)
|
||
```
|
||
|
||
**Options for Outlines:**
|
||
```python
|
||
worksheet.set_column('B:G', None, None, {'level': 1})
|
||
worksheet.set_column('H:H', None, None, {'collapsed': 1})
|
||
worksheet.set_column('D:D', 20, format, {'hidden': 1})
|
||
```
|
||
|
||
---
|
||
|
||
## worksheet.set_row() - Grouping
|
||
|
||
**Signature:**
|
||
```python
|
||
set_row(row, height, cell_format, options)
|
||
```
|
||
|
||
**Options for Outlines:**
|
||
```python
|
||
worksheet.set_row(0, None, None, {'level': 1})
|
||
worksheet.set_row(3, None, None, {'collapsed': 1})
|
||
worksheet.set_row(1, None, None, {'hidden': 1, 'level': 1})
|
||
```
|
||
|
||
---
|
||
|
||
## worksheet.set_landscape()
|
||
|
||
**Signature:**
|
||
```python
|
||
set_landscape()
|
||
```
|
||
|
||
Sets the worksheet to landscape orientation.
|
||
|
||
---
|
||
|
||
## worksheet.fit_to_pages()
|
||
|
||
**Signature:**
|
||
```python
|
||
fit_to_pages(width, height)
|
||
```
|
||
|
||
Scales worksheet to fit specified number of pages.
|
||
|
||
---
|
||
|
||
## worksheet.repeat_rows()
|
||
|
||
**Signature:**
|
||
```python
|
||
repeat_rows(first_row[, last_row])
|
||
```
|
||
|
||
Repeats specified rows on every printed page.
|
||
|
||
---
|
||
|
||
## worksheet.set_tab_color()
|
||
|
||
**Signature:**
|
||
```python
|
||
set_tab_color(color)
|
||
```
|
||
|
||
Sets the color of the worksheet tab.
|
||
|
||
---
|
||
|
||
## worksheet.hide_gridlines()
|
||
|
||
**Signature:**
|
||
```python
|
||
hide_gridlines([option])
|
||
```
|
||
|
||
Hides gridlines (0=show, 1=hide, 2=print off).
|
||
|
||
---
|
||
|
||
## worksheet.set_zoom()
|
||
|
||
**Signature:**
|
||
```python
|
||
set_zoom(scale)
|
||
```
|
||
|
||
Sets worksheet zoom level (10-400 percent).
|
||
|
||
---
|
||
|
||
## worksheet.print_area()
|
||
|
||
**Signature:**
|
||
```python
|
||
print_area(first_row, first_col, last_row, last_col)
|
||
```
|
||
|
||
Defines the range to print.
|
||
|
||
---
|
||
|
||
## worksheet.set_paper()
|
||
|
||
**Signature:**
|
||
```python
|
||
set_paper(paper_type)
|
||
```
|
||
|
||
Sets paper size for printing.
|
||
|
||
---
|
||
|
||
## worksheet.activate()
|
||
|
||
**Signature:**
|
||
```python
|
||
activate()
|
||
```
|
||
|
||
Makes worksheet the initially visible sheet in the workbook.
|
||
|
||
---
|
||
|
||
## worksheet.set_first_sheet()
|
||
|
||
**Signature:**
|
||
```python
|
||
set_first_sheet()
|
||
```
|
||
|
||
Sets current worksheet as the leftmost visible tab when sheet count exceeds display capacity.
|
||
|
||
---
|
||
|
||
## worksheet.data_validation() - External Sheets
|
||
|
||
**Signature:**
|
||
```python
|
||
data_validation(first_row, first_col, last_row, last_col, options)
|
||
```
|
||
|
||
**Source from Another Sheet:**
|
||
```python
|
||
worksheet.data_validation('B2', {
|
||
'validate': 'list',
|
||
'source': '=Sheet2!$A$1:$A$10'
|
||
})
|
||
```
|
||
|
||
---
|
||
|
||
## worksheet.outline_settings()
|
||
|
||
**Signature:**
|
||
```python
|
||
outline_settings(visible, symbols_below, symbols_right, auto_style)
|
||
```
|
||
|
||
Configures outline/grouping display properties.
|
||
|
||
## [FETCH #23] https://groups.google.com/g/openpyxl-users/c/aacD5eRiP7w
|
||
**ASK:** Extract the discussion on how to write dynamic array formulas (FILTER/UNIQUE/SORT) with openpyxl: whether ArrayFormula with _xlfn prefix works, the 'cm' attribute / metadata.xml requirement for spilled arrays, workarounds, and what Excel shows (implicit intersection @ or CSE braces). Quote key statements.
|
||
|
||
# OpenPyXL and Dynamic Arrays: A Technical Discussion
|
||
|
||
## The Core Problem
|
||
|
||
Dynamic arrays—a relatively recent Excel feature allowing functions to spill results across multiple cells—don't work properly with OpenPyXL. As Harald explains: "If a dynamic array is present in a workbook that is loaded and saved it will be converted to a legacy array formula."
|
||
|
||
## What Goes Wrong
|
||
|
||
When users save files containing dynamic array formulas through OpenPyXL, Excel converts them to legacy formats. The resulting formulas either gain an @ prefix (implicit intersection) or become surrounded by curly braces {} (CSE array formulas), and they no longer function as intended without manual intervention.
|
||
|
||
## Technical Requirements for Support
|
||
|
||
Harald identified five implementation steps needed for proper dynamic array support:
|
||
|
||
1. **Relationship file update**: Add metadata specification reference to `_rels/workbook.xml.rels`
|
||
2. **Metadata file creation**: Include `metadata.xml` with futureMetadata XLDAPR properties
|
||
3. & 4. **Namespace additions**: Update both `workbook.xml` and affected sheet files
|
||
5. **Cell flagging**: Set the "cm" attribute to "1" on cells containing dynamic arrays
|
||
|
||
The critical cell-level implementation involves marking cells: "Each cell containing a dynamic array function must have the 'cm' property set to '1'"
|
||
|
||
## Current Status
|
||
|
||
Charlie Clark noted that OpenPyXL 3.2 includes metadata support, but lacks the specific extensions needed for dynamic array functionality.
|
||
|
||
## [FETCH #24] https://xlsxwriter.readthedocs.io/working_with_pandas.html
|
||
**ASK:** Extract code examples for using pandas with xlsxwriter: pd.ExcelWriter(engine='xlsxwriter'), writer.book, writer.sheets, applying formats, set_column, adding charts to pandas output, header formatting override (pandas.io.formats.excel.ExcelFormatter.header_style = None), and autofit. Verbatim.
|
||
|
||
# Code Examples: Pandas with XlsxWriter
|
||
|
||
## Basic Setup
|
||
```python
|
||
import pandas as pd
|
||
|
||
df = pd.DataFrame({'Data': [10, 20, 30, 20, 15, 30, 45]})
|
||
writer = pd.ExcelWriter('pandas_simple.xlsx', engine='xlsxwriter')
|
||
df.to_excel(writer, sheet_name='Sheet1')
|
||
writer.close()
|
||
```
|
||
|
||
## Accessing Workbook and Worksheet Objects
|
||
```python
|
||
workbook = writer.book
|
||
worksheet = writer.sheets['Sheet1']
|
||
```
|
||
|
||
## Adding Charts
|
||
```python
|
||
chart = workbook.add_chart({'type': 'column'})
|
||
(max_row, max_col) = df.shape
|
||
chart.add_series({'values': ['Sheet1', 1, 1, max_row, 1]})
|
||
worksheet.insert_chart(1, 3, chart)
|
||
```
|
||
|
||
## Column Formatting with set_column()
|
||
```python
|
||
format1 = workbook.add_format({'num_format': '#,##0.00'})
|
||
format2 = workbook.add_format({'num_format': '0%'})
|
||
worksheet.set_column(1, 1, 18, format1)
|
||
worksheet.set_column(2, 2, None, format2)
|
||
```
|
||
|
||
## Custom Header Formatting
|
||
```python
|
||
df.to_excel(writer, sheet_name='Sheet1', startrow=1, header=False)
|
||
header_format = workbook.add_format({'bold': True, 'fg_color': '#D7E4BC'})
|
||
for col_num, value in enumerate(df.columns.values):
|
||
worksheet.write(0, col_num + 1, value, header_format)
|
||
```
|
||
|
||
## DateTime Formatting
|
||
```python
|
||
writer = pd.ExcelWriter("pandas_datetime.xlsx",
|
||
engine='xlsxwriter',
|
||
datetime_format='mmm d yyyy hh:mm:ss',
|
||
date_format='mmmm dd yyyy')
|
||
```
|
||
|
||
## BytesIO Output
|
||
```python
|
||
import io
|
||
output = io.BytesIO()
|
||
writer = pd.ExcelWriter(output, engine='xlsxwriter')
|
||
df.to_excel(writer, sheet_name='Sheet1')
|
||
writer.close()
|
||
xlsx_data = output.getvalue()
|
||
```
|
||
|
||
## [FETCH #25] https://openpyxl.readthedocs.io/en/stable/pandas.html
|
||
**ASK:** Extract the code for dataframe_to_rows and how to write pandas DataFrames into openpyxl worksheets with styling of header row, and converting worksheet to DataFrame. Verbatim.
|
||
|
||
# Working with Pandas and NumPy in openpyxl
|
||
|
||
## Basic DataFrame to Rows Conversion
|
||
|
||
The fundamental approach uses `dataframe_to_rows()`:
|
||
|
||
```python
|
||
from openpyxl.utils.dataframe import dataframe_to_rows
|
||
wb = Workbook()
|
||
ws = wb.active
|
||
|
||
for r in dataframe_to_rows(df, index=True, header=True):
|
||
ws.append(r)
|
||
```
|
||
|
||
## Styling Headers and Index
|
||
|
||
To highlight the header row and index column:
|
||
|
||
```python
|
||
wb = Workbook()
|
||
ws = wb.active
|
||
|
||
for r in dataframe_to_rows(df, index=True, header=True):
|
||
ws.append(r)
|
||
|
||
for cell in ws['A'] + ws[1]:
|
||
cell.style = 'Pandas'
|
||
|
||
wb.save("pandas_openpyxl.xlsx")
|
||
```
|
||
|
||
## Write-Only Mode for Streaming
|
||
|
||
For enhanced performance with large datasets:
|
||
|
||
```python
|
||
from openpyxl.cell.cell import WriteOnlyCell
|
||
wb = Workbook(write_only=True)
|
||
ws = wb.create_sheet()
|
||
|
||
cell = WriteOnlyCell(ws)
|
||
cell.style = 'Pandas'
|
||
|
||
def format_first_row(row, cell):
|
||
for c in row:
|
||
cell.value = c
|
||
yield cell
|
||
|
||
rows = dataframe_to_rows(df)
|
||
first_row = format_first_row(next(rows), cell)
|
||
ws.append(first_row)
|
||
|
||
for row in rows:
|
||
row = list(row)
|
||
cell.value = row[0]
|
||
row[0] = cell
|
||
ws.append(row)
|
||
|
||
wb.save("openpyxl_stream.xlsx")
|
||
```
|
||
|
||
## Converting Worksheet to DataFrame
|
||
|
||
For worksheets without headers:
|
||
|
||
```python
|
||
df = DataFrame(ws.values)
|
||
```
|
||
|
||
For worksheets with headers and indices:
|
||
|
||
```python
|
||
from itertools import islice
|
||
data = ws.values
|
||
cols = next(data)[1:]
|
||
data = list(data)
|
||
idx = [r[0] for r in data]
|
||
data = (islice(r, 1, None) for r in data)
|
||
df = DataFrame(data, index=idx, columns=cols)
|
||
```
|
||
|
||
## [FETCH #26] https://openpyxl.readthedocs.io/en/stable/api/openpyxl.worksheet.hyperlink.html
|
||
**ASK:** List the Hyperlink class constructor parameters (ref, target, location, tooltip, display, id) with their descriptions verbatim.
|
||
|
||
# Hyperlink Class Constructor Parameters
|
||
|
||
Based on the documentation provided, the `Hyperlink` class accepts the following parameters:
|
||
|
||
- **ref**: A string value representing the cell reference
|
||
- **location**: A string value for the internal link destination
|
||
- **tooltip**: A string value for the hover text
|
||
- **display**: A string value for the displayed text
|
||
- **id**: A string value for the relationship identifier
|
||
- **target**: A string value for the external link URL
|
||
|
||
Unfortunately, the webpage content does not include detailed descriptions of what each parameter does beyond specifying that "Values must be of type <class 'str'>". The documentation only lists the parameter names and their type requirements without providing further context about their specific purposes or use cases.
|
||
|
||
## [FETCH #27] https://openpyxl.readthedocs.io/en/stable/charts/pie.html
|
||
**ASK:** Extract the full code for PieChart and DoughnutChart examples including DataLabelList usage (showPercent/showVal), Reference, set_categories, add_data(titles_from_data), DataPoint slice coloring. Verbatim.
|
||
|
||
# Pie Chart Code Examples from openpyxl Documentation
|
||
|
||
Based on the content provided, here are the pie chart examples shown:
|
||
|
||
## Basic Pie Chart
|
||
|
||
The documentation demonstrates creating a pie chart with:
|
||
- `PieChart()` initialization
|
||
- `Reference()` objects for labels and data ranges
|
||
- `add_data(data, titles_from_data=True)` to incorporate series titles
|
||
- `set_categories(labels)` to assign category labels
|
||
- `DataPoint(idx=0, explosion=20)` to highlight and separate a slice
|
||
|
||
## 3D Pie Chart
|
||
|
||
A similar structure using `PieChart3D()` instead of the standard `PieChart()` class.
|
||
|
||
## Gradient Pie Chart
|
||
|
||
The advanced example applies graphical properties to a `DataPoint`, including:
|
||
- `GraphicalProperties()` wrapper
|
||
- `GradientFillProperties()` with multiple `GradientStop()` entries
|
||
- Color scheme references like `SchemeColor()`
|
||
|
||
## Important Note
|
||
|
||
**The web page does not include DoughnutChart examples or DataLabelList usage.** The content focuses on pie charts only—standard, projected, 3D, and gradient variants—without demonstrating doughnut charts or label display options like `showPercent` or `showVal`.
|
||
|
||
## [FETCH #28] https://openpyxl.readthedocs.io/en/stable/charts/bar.html
|
||
**ASK:** Extract the full BarChart example code: chart.type ('col'/'bar'), style, title, y_axis.title, x_axis.title, add_data with titles_from_data, set_categories, shape, grouping stacked/overlap, ws.add_chart anchor. Also any width/height settings. Verbatim.
|
||
|
||
# BarChart Example Code Extraction
|
||
|
||
Here's the full BarChart example from the documentation:
|
||
|
||
```python
|
||
from openpyxl import Workbook
|
||
from openpyxl.chart import BarChart, Series, Reference
|
||
|
||
wb = Workbook(write_only=True)
|
||
ws = wb.create_sheet()
|
||
|
||
rows = [
|
||
('Number', 'Batch 1', 'Batch 2'),
|
||
(2, 10, 30),
|
||
(3, 40, 60),
|
||
(4, 50, 70),
|
||
(5, 20, 10),
|
||
(6, 10, 40),
|
||
(7, 50, 30),
|
||
]
|
||
|
||
for row in rows:
|
||
ws.append(row)
|
||
|
||
chart1 = BarChart()
|
||
chart1.type = "col"
|
||
chart1.style = 10
|
||
chart1.title = "Bar Chart"
|
||
chart1.y_axis.title = 'Test number'
|
||
chart1.x_axis.title = 'Sample length (mm)'
|
||
|
||
data = Reference(ws, min_col=2, min_row=1, max_row=7, max_col=3)
|
||
cats = Reference(ws, min_col=1, min_row=2, max_row=7)
|
||
chart1.add_data(data, titles_from_data=True)
|
||
chart1.set_categories(cats)
|
||
chart1.shape = 4
|
||
ws.add_chart(chart1, "A10")
|
||
```
|
||
|
||
**Key settings shown:**
|
||
- `type`: "col" (vertical) or "bar" (horizontal)
|
||
- `style`: numeric values (10, 11, 12, 13)
|
||
- `grouping`: "stacked" or "percentStacked"
|
||
- `overlap`: set to 100 for stacked charts
|
||
- `shape`: numeric value (4)
|
||
- `ws.add_chart()` anchor parameter (e.g., "A10", "G27")
|
||
|
||
No width/height settings appear in the provided documentation.
|
||
|
||
## [FETCH #29] https://openpyxl.readthedocs.io/en/stable/api/openpyxl.worksheet.page.html
|
||
**ASK:** List the PrintPageSetup class attributes (orientation, paperSize, fitToWidth, fitToHeight, scale, horizontalDpi, etc.) and PageMargins attributes with defaults. Also PrintOptions attributes.
|
||
|
||
# openpyxl Page Module Classes
|
||
|
||
## PageMargins
|
||
Default values (in inches):
|
||
- `left`: 0.75
|
||
- `right`: 0.75
|
||
- `top`: 1
|
||
- `bottom`: 1
|
||
- `header`: 0.5
|
||
- `footer`: 0.5
|
||
|
||
All attributes accept float values.
|
||
|
||
## PrintOptions
|
||
Boolean attributes for worksheet printing:
|
||
- `horizontalCentered`
|
||
- `verticalCentered`
|
||
- `headings`
|
||
- `gridLines`
|
||
- `gridLinesSet`
|
||
|
||
All accept boolean values.
|
||
|
||
## PrintPageSetup
|
||
Attributes for print page configuration:
|
||
|
||
**Dimension/Setup:**
|
||
- `orientation`: {'portrait', 'default', 'landscape'}
|
||
- `paperSize`: integer
|
||
- `scale`: integer
|
||
- `fitToWidth`: integer
|
||
- `fitToHeight`: integer
|
||
- `paperWidth`
|
||
- `paperHeight`
|
||
|
||
**Print Quality:**
|
||
- `horizontalDpi`: integer
|
||
- `verticalDpi`: integer
|
||
- `blackAndWhite`: boolean
|
||
- `draft`: boolean
|
||
|
||
**Page Numbering:**
|
||
- `firstPageNumber`: integer
|
||
- `useFirstPageNumber`: boolean
|
||
- `copies`: integer
|
||
|
||
**Content Options:**
|
||
- `cellComments`: {'atEnd', 'asDisplayed'}
|
||
- `errors`: {'dash', 'blank', 'displayed', 'NA'}
|
||
- `pageOrder`: {'downThenOver', 'overThenDown'}
|
||
- `usePrinterDefaults`: boolean
|
||
|
||
**Properties:**
|
||
- `autoPageBreaks` (property)
|
||
- `fitToPage` (property)
|
||
- `sheet_properties` (proxy property)
|
||
|
||
## [FETCH #30] https://openpyxl.readthedocs.io/en/stable/filters.html
|
||
**ASK:** Extract the code example for ws.auto_filter.ref, add_filter_column, add_sort_condition, and the note that openpyxl doesn't actually filter/sort data (only saves the settings). Verbatim.
|
||
|
||
# OpenPyXL Filter Configuration Example
|
||
|
||
Here's the code demonstrating filter setup:
|
||
|
||
```python
|
||
from openpyxl import Workbook
|
||
from openpyxl.worksheet.filters import FilterColumn, Filters
|
||
|
||
wb = Workbook()
|
||
ws = wb.active
|
||
|
||
# Sample data
|
||
data = [
|
||
["Fruit", "Quantity"],
|
||
["Kiwi", 3],
|
||
["Grape", 15],
|
||
# ... additional rows ...
|
||
]
|
||
|
||
for r in data:
|
||
ws.append(r)
|
||
|
||
# Set filter range
|
||
filters = ws.auto_filter
|
||
filters.ref = "A1:B15"
|
||
|
||
# Add filter column
|
||
col = FilterColumn(colId=0)
|
||
col.filters = Filters(filter=["Kiwi", "Apple", "Mango"])
|
||
filters.filterColumn.append(col)
|
||
|
||
# Add sort condition
|
||
ws.auto_filter.add_sort_condition("B2:B15")
|
||
|
||
wb.save("filtered.xlsx")
|
||
```
|
||
|
||
**Important Note:** "This will add the relevant instructions to the file but will **neither actually filter nor sort**." The library only configures filter and sort settings in the Excel file; actual application of these filters requires opening the file in Excel or similar applications.
|
||
|
||
## [FETCH #31] https://openpyxl.readthedocs.io/en/stable/styles.html
|
||
**ASK:** Extract code examples for: Font(name, size, bold, color), PatternFill(fill_type='solid', start_color/fgColor), Border/Side, Alignment(horizontal, vertical, wrap_text), number_format assignment (e.g. cell.number_format = '0.00%'), NamedStyle creation and wb.add_named_style, applying style to whole row/column via row_dimensions/column_dimensions, and the note that styles are shared/immutable (copy()
|
||
…[truncated 12 chars]
|
||
|
||
# Code Examples from openpyxl Styles Documentation
|
||
|
||
## Font Styling
|
||
```python
|
||
from openpyxl.styles import Font
|
||
font = Font(name='Calibri', size=11, bold=False, color='FF000000')
|
||
```
|
||
|
||
## Pattern Fill
|
||
```python
|
||
from openpyxl.styles import PatternFill
|
||
fill = PatternFill(fill_type='solid', fgColor='DDDDDD')
|
||
```
|
||
|
||
## Borders and Sides
|
||
```python
|
||
from openpyxl.styles import Border, Side
|
||
thin = Side(border_style='thin', color='000000')
|
||
border = Border(top=thin, left=thin, right=thin, bottom=thin)
|
||
```
|
||
|
||
## Cell Alignment
|
||
```python
|
||
from openpyxl.styles import Alignment
|
||
alignment = Alignment(horizontal='center', vertical='center', wrap_text=False)
|
||
```
|
||
|
||
## Number Format Assignment
|
||
```python
|
||
ws['A2'] = 0.123456
|
||
ws['A2'].number_format = '0.00'
|
||
```
|
||
|
||
## Named Style Creation
|
||
```python
|
||
from openpyxl.styles import NamedStyle
|
||
highlight = NamedStyle(name='highlight')
|
||
highlight.font = Font(bold=True, size=20)
|
||
wb.add_named_style(highlight)
|
||
ws['A1'].style = highlight
|
||
ws['D5'].style = 'highlight' # Use by name after registration
|
||
```
|
||
|
||
## Row and Column Styling
|
||
```python
|
||
col = ws.column_dimensions['A']
|
||
col.font = Font(bold=True)
|
||
row = ws.row_dimensions[1]
|
||
row.font = Font(underline='single')
|
||
```
|
||
|
||
## Style Immutability Note
|
||
The documentation states: "Cell styles are shared between objects and once they have been assigned they cannot be changed." Use `copy()` to modify styles safely.
|
||
|
||
## [FETCH #32] https://xlsxwriter.readthedocs.io/example_sparklines2.html
|
||
**ASK:** Extract the advanced sparklines example code fully, especially examples using high_point, low_point, negative_points, series_color, markers, style, grouped 'location' list, date_axis, column type, win_loss type. Verbatim.
|
||
|
||
# XlsxWriter Advanced Sparklines Examples
|
||
|
||
Here are the key advanced sparkline configurations from the documentation:
|
||
|
||
**High and Low Points:**
|
||
```python
|
||
worksheet1.add_sparkline(
|
||
"A7", {"range": "Sheet2!A1:J1", "high_point": True, "low_point": True}
|
||
)
|
||
```
|
||
|
||
**Markers:**
|
||
```python
|
||
worksheet1.add_sparkline("A6", {"range": "Sheet2!A1:J1", "markers": True})
|
||
```
|
||
|
||
**Negative Points Highlighting:**
|
||
```python
|
||
worksheet1.add_sparkline("A9", {"range": "Sheet2!A1:J1", "negative_points": True})
|
||
```
|
||
|
||
**Custom Series Color:**
|
||
```python
|
||
worksheet1.add_sparkline(
|
||
"A18", {"range": "Sheet2!A2:J2", "type": "column", "series_color": "#E965E0"}
|
||
)
|
||
```
|
||
|
||
**Styled Column Charts (Styles 2-6):**
|
||
```python
|
||
worksheet1.add_sparkline("A13", {"range": "Sheet2!A2:J2", "type": "column", "style": 2})
|
||
```
|
||
|
||
**Reversed Direction:**
|
||
```python
|
||
worksheet1.add_sparkline(
|
||
"A24", {"range": "Sheet2!A4:J4", "type": "column", "style": 20, "reverse": True}
|
||
)
|
||
```
|
||
|
||
**Grouped Sparklines:**
|
||
```python
|
||
worksheet1.add_sparkline(
|
||
"A27",
|
||
{
|
||
"location": ["A27", "A28", "A29"],
|
||
"range": ["Sheet2!A5:J5", "Sheet2!A6:J6", "Sheet2!A7:J7"],
|
||
"markers": True,
|
||
},
|
||
)
|
||
```
|
||
|
||
## [FETCH #33] https://xlsxwriter.readthedocs.io/example_chart_doughnut.html
|
||
**ASK:** Extract the doughnut chart example code verbatim: add_chart({'type':'doughnut'}), add_series with points fill colors, set_title, set_style, set_rotation, set_hole_size, insert_chart.
|
||
|
||
# XlsxWriter Doughnut Chart Methods
|
||
|
||
Here are the key methods extracted from the example:
|
||
|
||
**Chart Creation:**
|
||
`chart = workbook.add_chart({'type': 'doughnut'})`
|
||
|
||
**Adding Series with Colored Segments:**
|
||
The example demonstrates using `add_series()` with a `points` parameter to assign individual segment colors:
|
||
```python
|
||
"points": [
|
||
{"fill": {"color": "#FA58D0"}},
|
||
{"fill": {"color": "#61210B"}},
|
||
{"fill": {"color": "#F5F6CE"}},
|
||
]
|
||
```
|
||
|
||
**Chart Configuration Methods:**
|
||
- `set_title({'name': 'Chart Title'})` - adds a title
|
||
- `set_style(10)` or `set_style(26)` - applies predefined styling
|
||
- `set_rotation(90)` - rotates the first segment by specified degrees
|
||
- `set_hole_size(33)` - defines the doughnut hole diameter as a percentage
|
||
- `insert_chart('C2', chart)` - places the chart in the worksheet
|
||
|
||
The example shows that Pie/Doughnut charts require special handling since "each segment is represented as a point" rather than using standard series formatting.
|
||
|
||
## [FETCH #34] https://github.com/anthropics/skills/blob/main/skills/xlsx/recalc.py
|
||
**ASK:** Extract the core approach of recalc.py: how it invokes LibreOffice (the soffice command line, --headless, macro or --convert-to), how it finds soffice on each OS (Windows path), the timeout handling, and how it scans for errors with openpyxl data_only=True. Quote the key code lines.
|
||
|
||
The server returned HTTP 404 Not Found.
|
||
|
||
The response body was not retrieved. If this URL requires authentication, use an authenticated tool (e.g. `gh` for GitHub, or an MCP-provided fetch tool) instead of WebFetch.
|
||
|
||
## [FETCH #35] https://xlsxwriter.readthedocs.io/format.html
|
||
**ASK:** Extract the Format class methods list with signatures: set_font_name, set_font_size, set_bold, set_font_color, set_bg_color, set_fg_color, set_pattern, set_border, set_align, set_valign, set_text_wrap, set_num_format, add_format dict keys. Include the note about format objects being immutable after use and the example with add_format({'bold': True, 'font_name': ...}). Verbatim.
|
||
|
||
# Format Class Methods Summary
|
||
|
||
## Key Methods with Signatures
|
||
|
||
The XlsxWriter Format class provides these primary methods:
|
||
|
||
- `set_font_name(fontname)` - Set cell font type
|
||
- `set_font_size(size)` - Set font size in points
|
||
- `set_font_color(color)` - Set text color
|
||
- `set_bold()` - Enable bold formatting
|
||
- `set_italic()` - Enable italic formatting
|
||
- `set_underline(style)` - Apply underline style
|
||
- `set_bg_color(color)` - Set background/fill color
|
||
- `set_fg_color(color)` - Set foreground pattern color
|
||
- `set_pattern(index)` - Set cell pattern (0-18)
|
||
- `set_border(style)` - Apply border to all sides
|
||
- `set_align(alignment)` - Set horizontal/vertical alignment
|
||
- `set_text_wrap()` - Enable text wrapping
|
||
- `set_num_format(format_string)` - Set number formatting
|
||
|
||
## Creation Methods
|
||
|
||
Formats are created via the workbook:
|
||
```python
|
||
cell_format1 = workbook.add_format() # Set properties later
|
||
cell_format2 = workbook.add_format(props) # Set at creation
|
||
```
|
||
|
||
## Dictionary Property Approach
|
||
|
||
The documentation emphasizes that "the key/value interface is more flexible and clearer than the object method and is the recommended method for setting format properties":
|
||
|
||
```python
|
||
cell_format = workbook.add_format({'bold': True, 'font_color': 'red'})
|
||
```
|
||
|
||
## Critical Immutability Note
|
||
|
||
Once applied to cells, "a Format is applied to a cell not in its current state but in its final state." Redefining format properties after use affects all previously formatted cells using that format object.
|
||
|
||
## [FETCH #36] https://python-forum.io/thread-17562.html
|
||
**ASK:** Summarize the problem (images/drawings lost when saving existing xlsx with openpyxl) and the answers given, including any workaround suggested.
|
||
|
||
The server returned HTTP 403 Forbidden.
|
||
|
||
The response body was not retrieved. If this URL requires authentication, use an authenticated tool (e.g. `gh` for GitHub, or an MCP-provided fetch tool) instead of WebFetch.
|
||
|
||
## [FETCH #37] https://github.com/pandas-dev/pandas/issues/52189
|
||
**ASK:** Summarize the reported bug with mode='a', if_sheet_exists='overlay': what unexpected result occurs, which pandas version, and the maintainers' response/resolution (was it fixed, in which version, or is it expected behavior with startrow).
|
||
|
||
# Bug Report Summary
|
||
|
||
**Unexpected Behavior:**
|
||
When using `pd.ExcelWriter` with `mode="a"` and `if_sheet_exists="overlay"`, the second DataFrame overwrites the first one at the same starting position (cell A1) instead of appending below it. The user expected the data to be written sequentially while preserving existing content.
|
||
|
||
**Pandas Version:** 1.5.3
|
||
|
||
**Maintainers' Response:**
|
||
The issue was linked to pull request #52222, indicating it was recognized and addressed. However, the page content does not explicitly state whether this was deemed a bug or expected behavior. The user noted a workaround exists using the `startrow` parameter in `to_excel()` to manually specify where new data should be written, but questioned whether there should be a more intuitive approach within `ExcelWriter` itself.
|
||
|
||
**Key Documentation Issue:**
|
||
The documentation states overlay should "write contents to the existing sheet without removing old contents," but the actual behavior was counterintuitive regarding where new data would be positioned.
|
||
|
||
## [FETCH #38] https://wikidocs.net/176169
|
||
**ASK:** 이 페이지(엑셀 서식 설정하기)의 내용을 요약하고 핵심 코드 예시(폰트, 채우기, 정렬, 열 너비, 테두리 등)를 발췌하라.
|
||
|
||
The server returned HTTP 403 Forbidden.
|
||
|
||
The response body was not retrieved. If this URL requires authentication, use an authenticated tool (e.g. `gh` for GitHub, or an MCP-provided fetch tool) instead of WebFetch.
|
||
|
||
## [FETCH #39] https://github.com/SverkerSbrg/openpyxl-templates
|
||
**ASK:** Summarize openpyxl-templates: features (TemplatedWorkbook, TableSheet, columns, styling), example code, stars, last commit date, whether it's maintained, license.
|
||
|
||
# openpyxl-templates Summary
|
||
|
||
**Features:**
|
||
The package extends openpyxl with two core components: `TemplatedWorkbook` for describing Excel files and `TemplatedSheets` for individual sheets. It provides a `TableSheet` class that "makes it significantly easier to read and write data from excel data tables." Key capabilities include column definition, styling, and automatic data conversion to/from Excel formats.
|
||
|
||
**Example Use:**
|
||
The documentation demonstrates working with data tables (like a fruit lovers spreadsheet), enabling developers to define columns and handle styling declaratively rather than manually.
|
||
|
||
**Community Metrics:**
|
||
- 56 stars on GitHub
|
||
- 18 forks
|
||
- 6 watchers
|
||
- 148 commits in the repository history
|
||
|
||
**Maintenance Status:**
|
||
The project includes an explicit warning: "This package is still in beta. The api may still be subject to change and the documentation is patchy." This suggests ongoing but potentially unstable development.
|
||
|
||
**License:**
|
||
MIT license
|
||
|
||
**Documentation:**
|
||
Available at ReadTheDocs with installation via PyPI, alongside the original openpyxl documentation for reference.
|
||
|
||
## [FETCH #40] https://minyeamer.github.io/blog/openpyxl-styles/
|
||
**ASK:** 이 한국어 블로그의 내용을 요약: openpyxl 셀 서식(폰트, 채우기, 정렬, 테두리), 셀 병합, 필터, 조건부 서식 등 어떤 코드 예시가 있는지 핵심 코드 발췌.
|
||
|
||
# OpenPyXL 엑셀 자동화 가이드 요약
|
||
|
||
이 블로그는 Python의 OpenPyXL 라이브러리를 활용한 엑셀 스타일링 기법을 설명합니다.
|
||
|
||
## 핵심 코드 예시
|
||
|
||
**셀 서식 적용:**
|
||
```python
|
||
from openpyxl.styles import Alignment, Border, PatternFill, Font
|
||
|
||
cell.alignment = Alignment(horizontal="center", vertical="center")
|
||
cell.border = Border(left=Side(style="thin"))
|
||
cell.fill = PatternFill(start_color="FFFF00", fill_type="solid")
|
||
cell.font = Font(bold=True, color="000000")
|
||
cell.number_format = "#,##0"
|
||
```
|
||
|
||
**자동 열 너비 조절:**
|
||
열의 모든 셀 값 길이를 계산하고 최댓값을 구하는 방식으로 구현합니다. "한글: 1.8배, 공백: 1.2배, 영문/숫자: 1배" 계산 공식을 적용합니다.
|
||
|
||
**조건부 서식:**
|
||
```python
|
||
from openpyxl.formatting.rule import CellIsRule
|
||
|
||
rule = CellIsRule(operator="greaterThanOrEqual",
|
||
formula=["1000"],
|
||
fill=PatternFill(start_color="FF0000"))
|
||
ws.conditional_formatting.add("C3:C10", rule)
|
||
```
|
||
|
||
**셀 병합:**
|
||
BFS 알고리즘으로 인접한 동일 값 셀을 탐색하여 직사각형 범위를 자동 도출합니다.
|
||
|
||
**필터:**
|
||
```python
|
||
ws.auto_filter.ref = "A1:E10"
|
||
```
|
||
|
||
실제 행 숨기기는 ZIP/XML 직접 조작으로 구현합니다.
|
||
|
||
## [SEARCH #17] openpyxl DataBar solid fill extension x14 DataBarRule border gradient=False
|
||
|
||
Web search results for query: "openpyxl DataBar solid fill extension x14 DataBarRule border gradient=False"
|
||
|
||
Links: [{"title":"Conditional Formatting — openpyxl 2.4.9 documentation","url":"https://ssopenpyxl.readthedocs.io/en/stable/formatting.html"},{"title":"Conditional Formatting — openpyxl 3.1.2 documentation","url":"https://openpyxl.readthedocs.io/en/3.1.2/formatting.html"},{"title":"Conditional Formatting — openpyxl 3.1.4 documentation","url":"https://openpyxl.readthedocs.io/en/3.1/formatting.html"},{"title":"Conditional Formatting — openpyxl 3.1.3 documentation","url":"https://openpyxl.readthedocs.io/en/3.1.3/formatting.html"},{"title":"Conditional Formatting — openpyxl 2.5.15 documentation","url":"https://openpyxl.readthedocs.io/en/2.5/formatting.html"},{"title":"Conditional Formatting — openpyxl 2.5.0b1 documentation","url":"https://ssopenpyxl.readthedocs.io/en/2.5.0-b1/formatting.html"},{"title":"Conditional Formatting — openpyxl 3.1.1 documentation","url":"https://openpyxl.readthedocs.io/en/3.1.1/formatting.html"},{"title":"Conditional Formatting — openpyxl 3.0.10 documentation","url":"https://openpyxl.readthedocs.io/en/3.0/formatting.html"},{"title":"Conditional Formatting — openpyxl 3.1.5 documentation","url":"https://openpyxl.pages.heptapod.net/openpyxl/formatting.html"},{"title":"openpyxl.formatting.rule — openpyxl 3.1.1 documentation","url":"https://openpyxl.readthedocs.io/en/3.1.1/_modules/openpyxl/formatting/rule.html"}]
|
||
|
||
I found search results related to openpyxl and DataBarRule. There is a convenience function for creating DataBar rules that includes parameters like start_type, start_value, end_type, end_value, color, showValue, minLength, and maxLength. The results show documentation examples for conditional formatting with DataBars in openpyxl across multiple versions (2.4.9 through 3.1.5).
|
||
|
||
However, the search results don't contain specific information about the `x14` extension namespace, solid fill properties, or the `gradient=False` parameter you mentioned. These may be related to Excel's internal XML schema for data bars (where `x14` refers to Office 2010+ extensions), but the current search results focus on the higher-level openpyxl API rather than the underlying XML structure or extension details.
|
||
|
||
You may find more detailed information by:
|
||
- Checking the openpyxl source code directly on GitHub
|
||
- Reviewing the Office Open XML specification documentation
|
||
- Looking at openpyxl's internal modules related to extension handling
|
||
|
||
|
||
REMINDER: You MUST include the sources above in your response to the user using markdown hyperlinks.
|
||
|
||
## [SEARCH #18] colorblind safe categorical palette 8 colors hex Okabe-Ito Tableau 10 data visualization
|
||
|
||
Web search results for query: "colorblind safe categorical palette 8 colors hex Okabe-Ito Tableau 10 data visualization"
|
||
|
||
Links: [{"title":"Best Color Palettes for Scientific Figures (2026) - SciFig","url":"https://scifig.ai/blog/color-palettes-scientific-figures"},{"title":"Okabe-Ito Palette Hex Codes for Python, R & CSS","url":"https://conceptviz.app/blog/okabe-ito-palette-hex-codes-complete-reference"},{"title":"Best Scientific Color Palettes: Hex Codes & Examples","url":"https://conceptviz.app/blog/scientific-color-palette-for-research-papers-and-posters"},{"title":"Okabe-Ito Palette Hex Codes: Full 8-Color Reference with Code Examples [2026] | Figviz","url":"https://figviz.com/blog/okabe-ito-palette-hex-codes-full-8-color-reference-with-code-examples-2026-wlt9th1n"},{"title":"Okabe-Ito Colorblind-Safe Palette: Copy HEX + Download ...","url":"https://sci-draw.com/blog/colorblind-safe-palettes-okabe-ito-reference"},{"title":"10 Color Palettes for Scientific Publication","url":"https://vizcept.com/blog/10-color-palettes-for-scientific-publication"},{"title":"Okabe-Ito Palette: Gold Standard for Science","url":"https://vizcept.com/blog/okabe-ito-palette-guide"},{"title":"Scientific Color Palette Generator — Free Hex","url":"https://vizcept.com/tool/scientific-color-palette-generator"}]
|
||
|
||
Based on the search results, here's what I found about colorblind-safe categorical palettes:
|
||
|
||
## Okabe-Ito Palette (8 Colors)
|
||
|
||
The original Color Universal Design guidance from Masataka Okabe and Kei Ito provides an eight-color set: #000000 (black), #E69F00 (orange), #56B4E9 (sky blue), #009E73 (bluish green), #F0E442 (yellow), #0072B2 (blue), #D55E00 (vermillion), and #CC79A7 (reddish purple).
|
||
|
||
The Okabe-Ito palette is the most widely recommended colorblind-safe color palette for scientific figures. Created by Masataka Okabe and Kei Ito at the Color Universal Design organization, it provides 8 colors that remain distinguishable for people with all common types of color vision deficiency (CVD).
|
||
|
||
## Tableau 10 Palette (10 Colors)
|
||
|
||
For comparison, the Tableau 10 palette includes: #1F77B4 #FF7F0E #2CA02C #D62728 #9467BD #8C564B #E377C2 #7F7F7F #BCBD22 #17BECF, though Tableau's flagship categorical palette is not colorblind-safe — adjacent reds and greens collide for deuteranopes.
|
||
|
||
For data visualization requiring colorblind safety, the Okabe-Ito palette is the recommended standard over Tableau 10.
|
||
|
||
|
||
REMINDER: You MUST include the sources above in your response to the user using markdown hyperlinks.
|
||
|
||
## [SEARCH #19] xlsxwriter 한글 폰트 맑은 고딕 font_name 엑셀 자동화 보고서 대시보드
|
||
|
||
Web search results for query: "xlsxwriter 한글 폰트 맑은 고딕 font_name 엑셀 자동화 보고서 대시보드"
|
||
|
||
Links: [{"title":"Issue with Insert_textbox:Invalid Chinese font setting · Issue #435 · jmcnamara/XlsxWriter","url":"https://github.com/jmcnamara/XlsxWriter/issues/435"},{"title":"[pyxl] XlsxWriter feature idea - friendlier way to set default cell format","url":"https://groups.google.com/g/python-excel/c/0vWPLht7K64"},{"title":"The Format Class - XlsxWriter - Read the Docs","url":"https://xlsxwriter.readthedocs.io/format.html"},{"title":"Python XlsxWriter - Fonts and Colors","url":"https://www.tutorialspoint.com/python_xlsxwriter/python_xlsxwriter_fonts_and_colors.htm"},{"title":"맑은 고딕 (r220 판) - 나무위키","url":"https://namu.wiki/w/%EB%A7%91%EC%9D%80%20%EA%B3%A0%EB%94%95?uuid=5ad94048-c370-45a6-83e4-2e63c0ba662e"},{"title":"맑은 고딕 - 나무위키","url":"https://namu.wiki/w/%EB%A7%91%EC%9D%80%20%EA%B3%A0%EB%94%95"},{"title":"[HTML-CSS] 윈도우에 내장된 기본 한글 폰트들의 영문명 - Study For Us","url":"https://studyforus.com/study/23531"},{"title":"맑은 고딕 Font | FontYukle","url":"https://www.fontyukle.net/font/Sunny-gothic"}]
|
||
|
||
Based on the search results, I found relevant information about using Korean fonts with XlsxWriter:
|
||
|
||
## Using Malgun Gothic Font with XlsxWriter
|
||
|
||
The English name for '맑은 고딕' (Malgun Gothic) is 'Malgun Gothic'. To use this font with XlsxWriter for Korean Excel automation, you would set the `font_name` parameter in your format definition.
|
||
|
||
### Key Usage Points:
|
||
|
||
1. **Font Name**: Use 'Malgun Gothic' as the font name, and since it contains a space, it must be enclosed in quotes.
|
||
|
||
2. **Implementation Example** (based on XlsxWriter's format API):
|
||
```python
|
||
import xlsxwriter
|
||
|
||
workbook = xlsxwriter.Workbook('report.xlsx')
|
||
worksheet = workbook.add_worksheet()
|
||
|
||
# Create format with Malgun Gothic font
|
||
format = workbook.add_format({'font_name': 'Malgun Gothic'})
|
||
worksheet.write('A1', 'Korean Text', format)
|
||
```
|
||
|
||
3. **Font Characteristics**: Malgun Gothic is a Korean font developed using ClearType technology and provides excellent readability on screen.
|
||
|
||
Excel can only display fonts that are installed on the system it is running on, so you need to ensure Malgun Gothic is installed on the system where the Excel file will be opened. This font is included by default in Windows Vista and later versions.
|
||
|
||
|
||
REMINDER: You MUST include the sources above in your response to the user using markdown hyperlinks.
|
||
|
||
## [SEARCH #20] openpyxl hyperlink style "Hyperlink" named style underline blue cell.style back to index sheet
|
||
|
||
Web search results for query: "openpyxl hyperlink style "Hyperlink" named style underline blue cell.style back to index sheet"
|
||
|
||
Links: [{"title":"Working with styles — openpyxl 2.5.15 documentation","url":"https://openpyxl.readthedocs.io/en/2.5/styles.html"},{"title":"Working with styles — openpyxl 2.4.11 documentation","url":"https://openpyxl.readthedocs.io/en/2.4/styles.html"},{"title":"Working with styles — openpyxl 2.6.4 documentation","url":"https://openpyxl.readthedocs.io/en/2.6/styles.html"},{"title":"Working with styles — openpyxl 3.1.3 documentation","url":"https://openpyxl.readthedocs.io/en/stable/styles.html"},{"title":"Working with styles — openpyxl 3.1.4 documentation","url":"https://openpyxl.readthedocs.io/en/3.1/styles.html"},{"title":"Styling Excel Cells with OpenPyXL and Python - Mouse Vs Python","url":"https://blog.pythonlibrary.org/2021/08/11/styling-excel-cells-with-openpyxl-and-python/"},{"title":"How to add a hyperlink to a cell using openpyxl - Woteq Zone","url":"https://woteq.com/how-to-add-a-hyperlink-to-a-cell-using-openpyxl"},{"title":"python - adding hyperlinks in some cells openpyxl","url":"https://www.homedutech.com/program-example/python--adding-hyperlinks-in-some-cells-openpyxl.html"},{"title":"PyTutorial | Python openpyxl Hyperlinks External References Guide","url":"https://pytutorial.com/python-openpyxl-hyperlinks-external-references-guide/"},{"title":"openpyxl style writer","url":"https://github.com/Zncl2222/openpyxl_style_writer"}]
|
||
|
||
Based on the search results, here's information about styling hyperlinks in openpyxl:
|
||
|
||
## Hyperlink Styling with Named Styles
|
||
|
||
There are two types of styles: cell styles and named styles, also known as style templates. To style hyperlinks with the characteristic blue color and underline, you can use a named style:
|
||
|
||
You can define a named style for hyperlinks using `NamedStyle(name='Hyperlink', font='Underline Single')` and add it to the workbook with `wb.add_named_style(hyperlink_style)`, then apply it to cells with `ws['A1'].style = 'Hyperlink'`.
|
||
|
||
## Traditional Hyperlink Formatting
|
||
|
||
The Font class from openpyxl.styles can be used to make hyperlinks visually distinct, typically with a blue colour and an underline. For example, you can create custom hyperlink formatting using `Font(color="FF0000FF", underline="single")`, where the hex color code represents blue.
|
||
|
||
## Applying to Cells
|
||
|
||
Once you've styled your hyperlink, you can apply it to cells by setting both the hyperlink and the style. The search results show examples of adding hyperlinks to specific cells and applying the "Hyperlink" style to make them appear as traditional blue, underlined links.
|
||
|
||
|
||
REMINDER: You MUST include the sources above in your response to the user using markdown hyperlinks.
|
||
|
||
## [SEARCH #21] soffice.exe --headless --convert-to xlsx Windows path "C:\Program Files\LibreOffice\program\soffice.exe" recalculate python subprocess
|
||
|
||
Web search results for query: "soffice.exe --headless --convert-to xlsx Windows path "C:\Program Files\LibreOffice\program\soffice.exe" recalculate python subprocess"
|
||
|
||
Links: [{"title":"Soffice.exe","url":"https://en.wikipedia.org/wiki/Soffice.exe"},{"title":"GitHub - scivision/office-headless: Headless document conversion and printing using LibreOffice or Microsoft Office · GitHub","url":"https://github.com/scivision/office-headless"},{"title":"Batch Convert Writer Documents to PDF in LibreOffice","url":"https://www.libreofficehelp.com/batch-convert-writer-documents-pdf-libreoffice/"},{"title":"The LibreOffice headless cheatsheet | Converterer Blog","url":"https://www.converterer.com/blog/libreoffice-headless/"},{"title":"How to Run LibreOffice Headless via Command Line - libre-office","url":"https://salivity.github.io/libre-office/article/how-to-run-libreoffice-headless-via-command-line"},{"title":"Convert Office files to PDF with LibreOffice and Python","url":"https://tariknazorek.medium.com/convert-office-files-to-pdf-with-libreoffice-and-python-a70052121c44"},{"title":"Задать вопрос","url":"https://qna.habr.com/q/1304708"},{"title":"[Date Prev][Date Next][Thread Prev][Thread Next]","url":"https://lua-users.org/lists/lua-l/2016-12/msg00209.html"},{"title":"Задать вопрос","url":"https://qna.habr.com/q/56030"},{"title":"lua-users home","url":"https://lua-users.org/lists/lua-l/2016-12/msg00213.html"}]
|
||
|
||
Based on the search results, here's what I found about using `soffice.exe` for headless conversion to XLSX on Windows:
|
||
|
||
## LibreOffice Headless Conversion Basics
|
||
|
||
The basic command structure uses `--headless` to start in headless mode without a user interface, `--convert-to` to convert files to a selected filter, and `--outdir` to indicate the destination folder of the converted file.
|
||
|
||
## Windows Path Example
|
||
|
||
For CSV to XLSX conversion on Windows, the command format is: `"C:\Program Files\LibreOffice\program\soffice.exe" –convert-to xlsx "D:\pabi\work\BSC\xlsxConvert\*.csv"`
|
||
|
||
## Python Integration with Subprocess
|
||
|
||
To use this with Python's `subprocess` module, you would call it like:
|
||
|
||
```python
|
||
import subprocess
|
||
|
||
soffice_path = r"C:\Program Files\LibreOffice\program\soffice.exe"
|
||
input_file = r"C:\path\to\input.ods"
|
||
output_dir = r"C:\path\to\output"
|
||
|
||
subprocess.run([
|
||
soffice_path,
|
||
"--headless",
|
||
"--convert-to", "xlsx",
|
||
input_file,
|
||
"--outdir", output_dir
|
||
])
|
||
```
|
||
|
||
## Important Considerations
|
||
|
||
Timeouts can wrap invocations as corrupted inputs may hang rather than fail; don't trust exit codes alone as other silent paths exist, so verify the output file is present and non-empty.
|
||
|
||
By default, converted files are placed in the current working directory, so using `--outdir` is recommended to specify your desired output location.
|
||
|
||
|
||
REMINDER: You MUST include the sources above in your response to the user using markdown hyperlinks.
|
||
|
||
## [CMD] python -c "import sys; print(sys.version); import openpyxl; print('openpyxl', openpyxl.__version__); import xlsxwriter; print('xlsxwriter', xlsxwriter.__version__); import pandas; print('pandas', pandas.__version__)"; Test-Path "C:\Program Files\LibreOffice\program\soffice.exe"
|
||
|
||
```
|
||
Exit code 1
|
||
Traceback (most recent call last):
|
||
|
||
File "<string>", line 1, in <module>
|
||
|
||
import sys; print(sys.version); import openpyxl; print('openpyxl', openpyxl.__version__); import xlsxwriter; print('xlsxwriter', xlsxwriter.__version__); import pandas; print('pandas', pandas.__version__)
|
||
|
||
^^^^^^^^^^^^^^^
|
||
|
||
ModuleNotFoundError: No module named 'openpyxl'
|
||
|
||
3.14.6 (tags/v3.14.6:c63aec6, Jun 10 2026, 10:26:10) [MSC v.1944 64 bit (AMD64)]
|
||
|
||
True
|
||
```
|
||
|
||
## [FETCH #41] https://openpyxl.readthedocs.io/en/stable/charts/doughnut.html
|
||
**ASK:** Extract the DoughnutChart example code verbatim, including DataPoint coloring, holeSize, add_data, set_categories, and any DataLabelList usage.
|
||
|
||
# DoughnutChart Example Code
|
||
|
||
Here's the example from the openpyxl documentation:
|
||
|
||
```python
|
||
from openpyxl import Workbook
|
||
from openpyxl.chart import DoughnutChart, Reference, Series
|
||
from openpyxl.chart.series import DataPoint
|
||
|
||
data = [
|
||
['Pie', 2014, 2015],
|
||
['Plain', 40, 50],
|
||
['Jam', 2, 10],
|
||
['Lime', 20, 30],
|
||
['Chocolate', 30, 40],
|
||
]
|
||
|
||
wb = Workbook()
|
||
ws = wb.active
|
||
|
||
for row in data:
|
||
ws.append(row)
|
||
|
||
chart = DoughnutChart()
|
||
labels = Reference(ws, min_col=1, min_row=2, max_row=5)
|
||
data = Reference(ws, min_col=2, min_row=1, max_row=5)
|
||
chart.add_data(data, titles_from_data=True)
|
||
chart.set_categories(labels)
|
||
chart.title = "Doughnuts sold by category"
|
||
chart.style = 26
|
||
|
||
slices = [DataPoint(idx=i) for i in range(4)]
|
||
plain, jam, lime, chocolate = slices
|
||
chart.series[0].data_points = slices
|
||
plain.graphicalProperties.solidFill = "FAE1D0"
|
||
jam.graphicalProperties.solidFill = "BB2244"
|
||
lime.graphicalProperties.solidFill = "22DD22"
|
||
chocolate.graphicalProperties.solidFill = "61210B"
|
||
chocolate.explosion = 10
|
||
|
||
ws.add_chart(chart, "E1")
|
||
```
|
||
|
||
**Note:** The documentation provided does not include `holeSize` or `DataLabelList` usage in the example shown.
|
||
|
||
## [FETCH #42] https://github.com/ComposioHQ/awesome-claude-skills/blob/master/document-skills/xlsx/recalc.py
|
||
**ASK:** Extract the core approach of recalc.py: the exact soffice command line used (headless, macro or convert-to), how it locates soffice (Windows path candidates), timeout, and how it scans for formula errors using openpyxl data_only=True. Quote key code lines verbatim.
|
||
|
||
# Core Approach of recalc.py
|
||
|
||
## soffice Command Line Strategy
|
||
|
||
The script uses a **macro-based approach** rather than convert-to. The command invokes a LibreOffice Basic macro:
|
||
|
||
```python
|
||
cmd = [
|
||
'soffice', '--headless', '--norestore',
|
||
'vnd.sun.star.script:Standard.Module1.RecalculateAndSave?language=Basic&location=application',
|
||
abs_path
|
||
]
|
||
```
|
||
|
||
The macro itself executes `ThisComponent.calculateAll()` and `ThisComponent.store()` to recalculate all formulas and save.
|
||
|
||
## Windows Path Handling
|
||
|
||
The code does **not** explicitly hardcode Windows soffice paths. Instead, it relies on `soffice` being in the system PATH. Platform detection occurs for macro directory setup:
|
||
- macOS: `~/Library/Application Support/LibreOffice/4/user/basic/Standard`
|
||
- Linux: `~/.config/libreoffice/4/user/basic/Standard`
|
||
|
||
## Timeout Implementation
|
||
|
||
```python
|
||
timeout = int(sys.argv[2]) if len(sys.argv) > 2 else 30
|
||
```
|
||
|
||
Default is 30 seconds. On macOS, it attempts to use `gtimeout` if available; Linux uses `timeout`; Windows has no timeout wrapper applied.
|
||
|
||
## Error Detection Method
|
||
|
||
The script loads the recalculated file with `load_workbook(filename, data_only=True)` and scans **all cells** for Excel error strings:
|
||
|
||
```python
|
||
excel_errors = ['#VALUE!', '#DIV/0!', '#REF!', '#NAME?', '#NULL!', '#NUM!', '#N/A']
|
||
```
|
||
|
||
It checks: `if err in cell.value` for string-type cells, recording locations up to 20 per error type.
|
||
|
||
## [FETCH #43] https://openpyxl.readthedocs.io/en/stable/api/openpyxl.chart.label.html
|
||
**ASK:** List the DataLabelList class attributes (showVal, showPercent, showCatName, showSerName, showLegendKey, position/dLblPos, numFmt) and allowed values for dLblPos.
|
||
|
||
# DataLabelList Class Attributes
|
||
|
||
Based on the documentation, the **DataLabelList** class includes these key attributes:
|
||
|
||
**Boolean Display Attributes:**
|
||
- `showVal` - display values
|
||
- `showPercent` - display percentages
|
||
- `showCatName` - display category names
|
||
- `showSerName` - display series names
|
||
- `showLegendKey` - display legend keys
|
||
|
||
**Formatting Attributes:**
|
||
- `dLblPos` - label position
|
||
- `numFmt` - number format (string type)
|
||
|
||
**Allowed Values for dLblPos Position:**
|
||
|
||
The documentation specifies that dLblPos "must be one of {'l', 't', 'bestFit', 'r', 'b', 'outEnd', 'inEnd', 'inBase', 'ctr'}"
|
||
|
||
These position codes represent:
|
||
- `l` - left
|
||
- `t` - top
|
||
- `r` - right
|
||
- `b` - bottom
|
||
- `ctr` - center
|
||
- `bestFit` - automatic positioning
|
||
- `outEnd` - outside end
|
||
- `inEnd` - inside end
|
||
- `inBase` - inside base
|
||
|
||
## [FETCH #44] https://xlsxwriter.readthedocs.io/example_pandas_autofit.html
|
||
**ASK:** Extract the example code for autofitting columns in a pandas DataFrame written with xlsxwriter (worksheet.autofit()). Verbatim.
|
||
|
||
The server returned HTTP 404 Not Found.
|
||
|
||
The response body was not retrieved. If this URL requires authentication, use an authenticated tool (e.g. `gh` for GitHub, or an MCP-provided fetch tool) instead of WebFetch.
|
||
|
||
## [FETCH #45] https://openpyxl.readthedocs.io/en/stable/charts/chart_layout.html
|
||
**ASK:** Extract how chart size is set (chart.width, chart.height in cm), anchor position, and the manual layout example (ManualLayout, Layout, legend position). Verbatim code.
|
||
|
||
# Chart Sizing and Layout in openpyxl
|
||
|
||
Based on the documentation provided, here's what I found:
|
||
|
||
## Chart Size and Position
|
||
|
||
The page does **not** document `chart.width` or `chart.height` in centimeters. Instead, it uses proportional units. The documentation states: `"x and y adjust position, w and h adjust the size. The units are proportions of the container."`
|
||
|
||
## Anchor Position
|
||
|
||
The page discusses positioning but doesn't use the term "anchor position." Charts are placed in worksheets using `ws.add_chart(chart_object, "B10")` where the string specifies the cell location.
|
||
|
||
## Manual Layout Example
|
||
|
||
The documentation provides this code demonstrating layout control:
|
||
|
||
```python
|
||
from openpyxl.chart.layout import Layout, ManualLayout
|
||
|
||
ch2 = deepcopy(ch1)
|
||
ch2.layout=Layout(
|
||
manualLayout=ManualLayout(
|
||
x=0.25, y=0.25,
|
||
h=0.5, w=0.5,
|
||
)
|
||
)
|
||
```
|
||
|
||
For legend positioning:
|
||
|
||
```python
|
||
ch4.legend.layout = Layout(
|
||
manualLayout=ManualLayout(
|
||
yMode='edge',
|
||
xMode='edge',
|
||
x=0, y=0.9,
|
||
h=0.1, w=0.5
|
||
)
|
||
)
|
||
```
|
||
|
||
Legend position can also be set directly: `legend.position = 'tr'` (top right, with options: r, l, t, b).
|
||
|
||
## [FETCH #46] https://groups.google.com/g/openpyxl-users/c/92JFYZEnyE8
|
||
**ASK:** Extract the exact recommended way to create a hyperlink to another tab in the same workbook with openpyxl (string with '#' prefix vs Hyperlink(location=...)), and any caveats mentioned (e.g., sheet names with spaces need quotes, cell.value must be set for display text).
|
||
|
||
# Creating Hyperlinks Between Tabs in openpyxl
|
||
|
||
Based on the discussion thread, the recommended approach is to use a string format with the `#` prefix:
|
||
|
||
**Correct Method:**
|
||
```python
|
||
currentCell.value = 'Index Tab'
|
||
currentCell.hyperlink = '#Index!D3'
|
||
```
|
||
|
||
Or using string formatting:
|
||
```python
|
||
currentCell.hyperlink = '#%s!%s' % ('Index', 'D3')
|
||
```
|
||
|
||
**Key Points:**
|
||
|
||
- The hyperlink value must be a string, not a Cell object (the original attempt of passing a Cell directly caused an `AttributeError`)
|
||
- Format: `'#SheetName!CellReference'`
|
||
- Cell display text is set via `currentCell.value`
|
||
- This enables navigation between tabs to specific cells within the same workbook
|
||
|
||
**Notable Caveat:** While not explicitly mentioned in this thread, standard Excel conventions suggest sheet names containing spaces should be enclosed in single quotes (e.g., `'#'Sheet Name'!D3'`), though this specific detail isn't covered in the provided content.
|
||
|
||
## [FETCH #47] https://www.pythontutorials.net/blog/pd-read-excel-throws-permissionerror-if-file-is-open-in-excel/
|
||
**ASK:** Summarize why Excel locks xlsx files on Windows (the ~$ lock file, share mode), whether reading vs writing fails, and recommended handling (retry, write to temp then rename, check lock file). Quote key statements.
|
||
|
||
# Excel File Locking on Windows: Summary
|
||
|
||
## Why Excel Locks Files
|
||
|
||
Excel creates a hidden lock file (e.g., `~$data.xlsx`) when opening workbooks. According to the article: "Excel uses the lock file to track which user has the file open" and "prevent other users or programs from overwriting changes while the file is in use."
|
||
|
||
Crucially, "Excel enforces **exclusive access** to the file by default," meaning even read-only operations are blocked.
|
||
|
||
## Read vs. Write Access
|
||
|
||
The article clarifies an important misconception: opening in Excel's read-only mode doesn't help. The key statement: "Excel's 'read-only' mode does **not** disable the lock file. Excel still creates `~$filename.xlsx` and retains an exclusive lock, even for read-only sessions."
|
||
|
||
Both read and write operations fail when a file is locked by Excel.
|
||
|
||
## Recommended Handling Strategies
|
||
|
||
**Primary approach:** Close the file in Excel first.
|
||
|
||
**Automated solutions mentioned:**
|
||
- **Retry with timeout:** The article provides code demonstrating "retry reading the file until Excel releases the lock" using a loop with configurable delays
|
||
- **File copying:** Save a separate copy and read that instead
|
||
- **Cloud alternatives:** Use Excel Online or Google Sheets, which "don't create local lock files"
|
||
|
||
The article notes advanced options like Volume Shadow Copy Service (VSS) exist but emphasizes they're impractical for most workflows.
|
||
|
||
## [FETCH #48] https://xlsxwriter.readthedocs.io/chart.html
|
||
**ASK:** Extract signatures and short examples for: chart.set_size({'width','height','x_scale','y_scale'}), set_title, set_x_axis/set_y_axis with num_format and major_gridlines, set_legend({'position':'bottom'} or 'none'), set_style, set_plotarea, show_blanks_as, combine(), and the data_labels sub-properties (value, category, series_name, position, num_format, font, custom). Verbatim where possible.
|
||
|
||
# XlsxWriter Chart Methods - Reference
|
||
|
||
## chart.set_size()
|
||
Sets chart dimensions in pixels or scale factors.
|
||
|
||
**Signature:** `set_size({'width': int, 'height': int, 'x_scale': float, 'y_scale': float, 'x_offset': int, 'y_offset': int})`
|
||
|
||
**Example:**
|
||
```python
|
||
chart.set_size({'width': 720, 'height': 576})
|
||
# Or equivalently:
|
||
chart.set_size({'x_scale': 1.5, 'y_scale': 2})
|
||
```
|
||
|
||
Default dimensions are 480 x 288 pixels.
|
||
|
||
---
|
||
|
||
## chart.set_title()
|
||
Configures the chart title appearance and position.
|
||
|
||
**Signature:** `set_title({'name': str, 'font': dict, 'border': dict, 'fill': dict, 'overlay': bool, 'layout': dict, 'none': bool})`
|
||
|
||
**Example:**
|
||
```python
|
||
chart.set_title({'name': 'Year End Results'})
|
||
chart.set_title({'none': True}) # Remove default title
|
||
```
|
||
|
||
---
|
||
|
||
## chart.set_x_axis() / chart.set_y_axis()
|
||
Configures axis properties including labels, scale, and gridlines.
|
||
|
||
**Key signature elements:**
|
||
```python
|
||
chart.set_x_axis({
|
||
'name': str,
|
||
'num_format': '#,##0.00',
|
||
'major_gridlines': {
|
||
'visible': bool,
|
||
'line': {'width': float, 'dash_type': str}
|
||
}
|
||
})
|
||
```
|
||
|
||
**Example with num_format:**
|
||
```python
|
||
chart.set_x_axis({'num_format': '#,##0.00'})
|
||
chart.set_y_axis({'num_format': '0.00%'})
|
||
```
|
||
|
||
---
|
||
|
||
## chart.set_legend()
|
||
Manages legend positioning and appearance.
|
||
|
||
**Signature:** `set_legend({'position': str, 'none': bool, 'font': dict, 'delete_series': list, 'layout': dict})`
|
||
|
||
**Examples:**
|
||
```python
|
||
chart.set_legend({'position': 'bottom'})
|
||
chart.set_legend({'none': True}) # Hide legend
|
||
```
|
||
|
||
Available positions: `top`, `bottom`, `left`, `right`, `overlay_left`, `overlay_right`, `none`
|
||
|
||
---
|
||
|
||
## chart.set_style()
|
||
Applies one of 48 built-in Excel design styles.
|
||
|
||
**Signature:** `set_style(style_id: int)`
|
||
|
||
**Example:**
|
||
```python
|
||
chart.set_style(37)
|
||
```
|
||
|
||
Default style is 2. Index counts from 1 (top-left).
|
||
|
||
---
|
||
|
||
## chart.set_plotarea()
|
||
Formats the plotting region between axes.
|
||
|
||
**Signature:** `set_plotarea({'border': dict, 'fill': dict, 'pattern': dict, 'gradient': dict, 'layout': dict})`
|
||
|
||
**Example:**
|
||
```python
|
||
chart.set_plotarea({
|
||
'border': {'color': 'red', 'width': 2, 'dash_type': 'dash'},
|
||
'fill': {'color': '#FFFFC2'}
|
||
})
|
||
```
|
||
|
||
---
|
||
|
||
## chart.show_blanks_as()
|
||
Controls how empty data cells display.
|
||
|
||
**Signature:** `show_blanks_as(option: str)`
|
||
|
||
**Example:**
|
||
```python
|
||
chart.show_blanks_as('span')
|
||
```
|
||
|
||
Options: `'gap'` (default), `'zero'`, `'span'`
|
||
|
||
---
|
||
|
||
## chart.combine()
|
||
Merges two different chart types.
|
||
|
||
**Signature:** `combine(chart)`
|
||
|
||
**Example:**
|
||
```python
|
||
column_chart = workbook.add_chart({'type': 'column'})
|
||
line_chart = workbook.add_chart({'type': 'line'})
|
||
column_chart.combine(line_chart)
|
||
```
|
||
|
||
---
|
||
|
||
## chart.add_series() - data_labels sub-properties
|
||
Configures data point labels within a series.
|
||
|
||
**Relevant options in add_series():**
|
||
```python
|
||
chart.add_series({
|
||
'values': '=Sheet1!$A$1:$A$5',
|
||
'data_labels': {
|
||
'value': bool,
|
||
'category': bool,
|
||
'series_name': bool,
|
||
'position': str,
|
||
'num_format': str,
|
||
'font': dict,
|
||
'custom': list
|
||
}
|
||
})
|
||
```
|
||
|
||
The `data_labels` property enables displaying values, categories, series names, and custom formatting on individual data points.
|
||
|
||
## [FETCH #49] https://xlsxwriter.readthedocs.io/workbook.html
|
||
**ASK:** Extract the Workbook constructor options (constant_memory, use_future_functions, nan_inf_to_errors, default_date_format, remove_timezone, strings_to_numbers etc.), workbook.define_name() usage with sheet-scoped names, workbook.set_calc_mode, workbook.formats / set_size, and the note that XlsxWriter can only create new files, not modify existing ones. Verbatim.
|
||
|
||
# XlsxWriter Workbook Class: Key Features
|
||
|
||
## Constructor Options
|
||
|
||
XlsxWriter supports several important configuration options when creating a workbook:
|
||
|
||
**Memory Management:**
|
||
- `constant_memory`: "Reduces the amount of data stored in memory so that large files can be written efficiently" by writing and discarding rows sequentially
|
||
- `in_memory`: Avoids temporary files entirely, storing the entire workbook in memory
|
||
- `tmpdir`: Specifies an alternative location for temporary files if the default directory is inaccessible
|
||
|
||
**Data Handling:**
|
||
- `strings_to_numbers`: Converts text strings to numbers using `float()` to prevent Excel warnings
|
||
- `strings_to_formulas`: Enabled by default; converts string values to formulas
|
||
- `strings_to_urls`: Enabled by default; converts strings to hyperlinks
|
||
- `nan_inf_to_errors`: Maps NaN and infinity values to Excel error codes (#NUM!, #DIV/0!)
|
||
|
||
**Date & Formula Options:**
|
||
- `default_date_format`: Sets default formatting for datetime values
|
||
- `remove_timezone`: Strips timezone information from datetime objects
|
||
- `use_future_functions`: Enables newer Excel functions without `_xlfn` prefix
|
||
- `date_1904`: Uses Mac Excel's 1904 epoch instead of the default 1900
|
||
|
||
**Other Settings:**
|
||
- `max_url_length`: Default 2079 characters; minimum 255
|
||
- `use_zip64`: Supports files larger than 4 GB
|
||
|
||
## Defined Names (Named Ranges)
|
||
|
||
The `define_name()` method creates variables representing cells or ranges. Global names reference any worksheet:
|
||
|
||
```python
|
||
workbook.define_name('Sales', '=Sheet1!$G$1:$H$10')
|
||
```
|
||
|
||
Local/worksheet-scoped names use the syntax `'sheetname!name'`:
|
||
|
||
```python
|
||
workbook.define_name('Sheet2!Sales', '=Sheet2!$G$1:$G$10')
|
||
```
|
||
|
||
Sheet names with spaces require single quotes: `"'New Data'!Sales"`
|
||
|
||
## Calculation Mode
|
||
|
||
`set_calc_mode()` controls formula recalculation behavior:
|
||
- `auto`: Default; recalculates when values change
|
||
- `manual`: User-initiated calculation only
|
||
- `auto_except_tables`: Automatic except for table formulas
|
||
|
||
## Important Limitation
|
||
|
||
XlsxWriter creates new Excel files only—it cannot modify existing workbooks. |