# A workbook of documents and counts by sector

The Python program to download, and any file it reads:

- [`sector_workbook.py`](/docs/examples/python/sector_workbook.py) (19.7 KB)

Example output, what the program wrote when it ran against the API, with the first rows of each file:

[`sectors-2026-09.xlsx`](/docs/examples/python/sectors-2026-09.xlsx) (776.3 KB)

Sheet Documents:

| Sector | Title (English) | Title (Chinese) | Document number | Summary | Level | Province | Type | Issuer | Department | Date | Date kind | Length | Source | ReConnect China | Id |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| Energy efficiency | Special Action Plan for Energy Conservation and Carbon Reduction in the Cement Industry | 《水泥行业节能降碳专项行动计划》 |  | The document announces a special action plan for energy conservation and carbon reduction in the cement industry, aiming to support the 14th Five-Year Plan ene… | centre |  | opinion/plan | 国家发展和改革委员会 |  | 2026-09-25 | added | 3366 | https://www.ndrc.gov.cn/xxgk/zcfb/tz/202406/P020240607579153428151.pdf | https://reconnectchina.org/items/6ab67afaed91061889a0d6dd/special-action-plan-for-energy-conservation-and-carbon-reduction-in-the-cement-industry | 6ab67afaed91061889a0d6dd |
| Energy efficiency | Special Action Plan for Energy Conservation and Carbon Reduction in the Steel Industry | 《钢铁行业节能降碳专项行动计划》 |  | The document announces a special action plan for energy conservation and carbon reduction in the steel industry, aiming to support the 14th Five-Year Plan ener… | centre |  | opinion/plan | 国家发展和改革委员会 |  | 2026-09-25 | added | 3963 | https://www.ndrc.gov.cn/xxgk/zcfb/tz/202406/P020240607588410867952.pdf | https://reconnectchina.org/items/6ab67aaaed91061889a0d6d2/special-action-plan-for-energy-conservation-and-carbon-reduction-in-the-steel-industry | 6ab67aaaed91061889a0d6d2 |
| Energy efficiency | Special Action Plan for Energy Conservation and Carbon Reduction in the Synthetic Ammonia Industry | 《合成氨行业节能降碳专项行动计划》 |  | The document announces a special action plan for energy conservation and carbon reduction in the synthetic ammonia industry, aiming to support the 14th Five-Ye… | centre |  | opinion/plan | 国家发展和改革委员会 |  | 2026-09-25 | added | 3025 | https://www.ndrc.gov.cn/xxgk/zcfb/tz/202406/P020240607582611433601.pdf | https://reconnectchina.org/items/6ab67ac3ed91061889a0d6d8/special-action-plan-for-energy-conservation-and-carbon-reduction-in-the-synthetic-ammonia-industry | 6ab67ac3ed91061889a0d6d8 |
| Energy efficiency | 2. Scoring Method for Energy Conservation Targets of 103 Key Energy-Using Enterprises | 2.考核103户重点用能企业节能目标计分办法 |  | This attachment sets out a scoring method for energy-saving targets of 103 key energy-consuming enterprises, with a total of 100 points. Key provisions: - \*\*E… | provinces | Shandong | regulation | 山东省 |  | 2026-09-25 | added | 1536 | http://www.shandong.gov.cn/jpolicypub/jpolicy_file/filedata/2023/03/28/5df1847f6a03486fbec5913a8ff4dd98.pdf | https://reconnectchina.org/items/6ab66e61ed91061889a0d56c/2-scoring-method-for-energy-conservation-targets-of-103-key-energy-using-enterprises | 6ab66e61ed91061889a0d56c |
| Energy efficiency | 1. Scoring Method for Evaluating the Energy Conservation Targets of Municipal Governments of Prefecture-Level Cities | 1.考核各设区市政府节能目标计分办法 |  | This attachment sets scoring rules for assessing energy-saving targets of municipal governments in Shandong Province. It lists 10 scoring items, each with a to… | cities | Shandong | regulation | 山东省 |  | 2026-09-25 | added | 1384 | http://www.shandong.gov.cn/jpolicypub/jpolicy_file/filedata/2023/02/13/ff63d140492b440e87365d997db46997.pdf | https://reconnectchina.org/items/6ab66e66ed91061889a0d56d/1-scoring-method-for-evaluating-the-energy-conservation-targets-of-municipal-governments-of | 6ab66e66ed91061889a0d56d |
| Energy efficiency | Sanya City Energy Conservation and Emission Reduction Office \[2014\] No. 5: Notice on the 2013 Sanya City Energy Conservation Work Assessment (Yang Pingfeng) | 三节能减排办〔2014〕5号：2013年度三亚市节能工作考核情况通报(杨平锋) | 三节能减排办〔2014〕5号 | The document is a notice (Sanya City Energy Conservation and Emission Reduction Office \[2014\] No. 5) issued by the Office of the Leading Group for Climate Chan… | cities | Hainan | notice/announcement | 海南省 |  | 2026-09-17 | added | 829 | https://www.sanya.gov.cn/attachment/cmsfile/kjgyxxhsite/zjgbxx/201503/daofile/3043_1505582310000.doc | https://reconnectchina.org/items/6aaad2a69220a9eac4c974d3/sanya-city-energy-conservation-and-emission-reduction-office-2014-no-5-notice-on-the-2013-sanya | 6aaad2a69220a9eac4c974d3 |

Sheet Counts:

| By level |  |  |  |  |  |
| --- | --- | --- | --- | --- | --- |
| Sector | Documents | centre | provinces | cities | other |
| Energy efficiency | 1105 | 113 | 145 | 847 | 0 |
| Carbon peaking and carbon neutrality | 409 | 36 | 54 | 319 | 0 |
| Digital economy | 1619 | 194 | 222 | 1203 | 0 |
| Wastewater treatment | 1007 | 72 | 101 | 834 | 0 |
| Elderly care (养老服务) | 1541 | 81 | 169 | 1291 | 0 |

## What it does

This program runs each sector's saved search for one month and writes a new Excel workbook.
Its first sheet lists every document a sector's search found, one row per document and sector,
with the title in English and Chinese, a summary, the document number, the issuing
department, the date, the length of the text and the links to the source and to ReConnect
China. Its second sheet counts the documents by sector, administrative level and province.

It is the monthly update of a register kept in Excel. The saved searches are the ones
*Saved searches from a keyword workbook* makes, one per sector, so the keywords stay in your
keyword sheet and this program only names the searches. The workbook is new every time: copy
its rows into your own register, or link to it from there.

## What you need

Python 3.11 or later, and the packages this program uses:

```sh
pip install reconnectchina openpyxl
```

Then run `python sector_workbook.py`. With uv, `uv run sector_workbook.py` installs what it needs by itself.

```python
import sys
from dataclasses import dataclass
from datetime import date, datetime, timedelta, timezone

from openpyxl import Workbook
from openpyxl.styles import Alignment, Font
from openpyxl.utils import get_column_letter
from openpyxl.worksheet.worksheet import Worksheet
from reconnectchina import (
    ApiError,
    Client,
    ConsolePrompt,
    Detail,
    HistogramRequests,
    Histograms,
    IssuerHistogramOptions,
    LevelHistogramOptions,
    RunSearchRequest,
    ScopeId,
    SearchFirstPage,
    SearchOverrides,
    SearchPage,
    Summary,
)
```

## What to run

`SAVED_SEARCHES` names the searches to run, one per sector, in the order the workbook lists
them, and `SCOPE` where they were saved: `account` for your own, `organization` for those
shared with everyone in your organization. A scope may hold other searches too, on other
subjects, and a shared one colleagues' searches; that is why the program runs the names you
list rather than all of them.

`MONTH` is the month to run them for, such as `"2026-08"`. Leave it at `None` for last month,
counted in China. Naming a month lets you run one you missed. The workbook is named after the
month: `sectors-2026-08.xlsx`.

`MAX_DOCUMENTS` is how many rows a sector gets at most: its most relevant documents, or its
newest when the saved search has no term. A register is read by people, and each 32 rows cost
a request for their detail, so a search that finds tens of thousands of documents a month is
better narrowed than written out. The counts cover every document either way.

```python
SAVED_SEARCHES = [
    "energy-efficiency",
    "碳达峰碳中和",
    "digital-economy",
    "wastewater",
    "elderly-care",
]
SCOPE: ScopeId = "account"
MONTH: str | None = None
MAX_DOCUMENTS = 200
```

## Dates in China

The API gives every date as an instant in UTC. A date a source page prints, such as
12 May 2026, is midnight in China, which is 16:00 UTC on 11 May. So the calendar date is taken
in China's time zone, UTC+8, or every printed date comes out a day early. China has kept that
one offset since 1991, so a fixed offset is enough.

The same goes for the month, and the API can work it out in China's time zone. The program
sends `2026-08-01[Asia/Shanghai]` as the search's `from`: a date followed by a time zone in
brackets is midnight at its start in that zone, 16:00 UTC on 31 July. It sends
`2026-08-01[Asia/Shanghai]+M` as `to`, one calendar month later in the same zone, the first
instant the search leaves out, so the month ends where the next one begins. `Asia/Shanghai` is
the name of China's time zone in the time zone database, and it has been UTC+8 since 1991, the
offset this program shows dates at.

```python
CHINA = timezone(timedelta(hours=8))


def china_date(instant: datetime | None) -> date | None:
    """The calendar date in China, or nothing when there is no date."""
    if instant is None:
        return None
    return instant.astimezone(CHINA).date()


def last_month(today: date) -> str:
    """The month before the one `today` is in, such as `2026-08`."""
    return f"{today.replace(day=1) - timedelta(days=1):%Y-%m}"


def month_window(month: str) -> tuple[str, str]:
    """Instant expressions for the first instant of `month` in China, and of the next month."""
    first = f"{month}-01[Asia/Shanghai]"
    return first, f"{first}+M"
```

## Finding the saved searches

Before it runs anything, the program looks up every name in `SAVED_SEARCHES`, which also
gives it each search's title. A name nobody has saved, or one misspelt here, would otherwise
stop the program halfway, after some sectors have run. Looking them up first lets it name
every missing search at once and write nothing.

When the API refuses a request, the client raises an `ApiError`, and its `type` says which
problem it was, such as `saved-search-not-found`: the API documentation's *Problem types*
lists each, with what to do about it. Branch on `type`, never on the message, which is written
for people to read and can change. Any other problem here, such as an account whose access
has ended, is not something this program can help with, so it is raised again and ends the
program with its message.

A saved search is looked up in `SCOPE` alone. One a colleague saved in their own `account` is
theirs, and not found in yours: to run it, they save it in `organization` and you set
`SCOPE = "organization"` (see *Saved searches from a keyword workbook*).

```python
def find_searches(client: Client) -> dict[str, str]:
    """The title of each saved search in `SAVED_SEARCHES`, by name."""
    titles: dict[str, str] = {}
    missing: list[str] = []
    for name in SAVED_SEARCHES:
        try:
            titles[name] = client.get_saved_search(SCOPE, name).title or name
        except ApiError as error:
            if error.type != "saved-search-not-found":
                raise
            missing.append(name)
    if missing:
        sys.exit(
            f"No saved search is called {', '.join(missing)} in the scope {SCOPE}. Save "
            "them with saved_searches_from_keywords.py, or change SAVED_SEARCHES or SCOPE."
        )
    return titles
```

## Running one sector's search

The search runs as it was saved, with the month's `from_` and `to` in place of its dates, so
it keeps to the kinds of document it was saved with: the policy documents. Its
title is the sector's name, as the keyword sheet gave it, and the workbook shows it in every
row, so that a formula such as `COUNTIF` can count a sector's rows.

The first page also brings the counts. `histograms` asks for them: how many of the search's
documents were issued at each administrative level, and how many come from each issuer. They
count every document the search matches, however far the paging below gets. To have only the
counts, without any documents, set `page_size=0`.

A document's issuer is the province it concerns, when ReConnect China's classifier finds one;
failing that, its city or county, or whoever runs the website it came from, such as a
ministry. So the issuers that are provinces give the counts by province.

Paging works as in *Search results as a CSV file*: follow `next` until a page comes without
it, and skip a document already seen. It also stops once the sector has `MAX_DOCUMENTS`. When
fewer documents are written than the search found, the program says so, and why: the limit
above, or a last page that carries `truncated`, such as at the depth your organization's
agreement allows a search to page to.

```python
@dataclass
class Sector:
    title: str
    hits: int
    levels: dict[str, int]
    provinces: dict[str, int]
    summaries: list[Summary]


def run(client: Client, name: str, title: str, month: str) -> Sector:
    start, end = month_window(month)
    first = client.run_saved_search(
        SCOPE,
        name,
        RunSearchRequest(
            parameters=SearchOverrides(
                from_=start,
                to=end,
                page_size=100,
                histograms=HistogramRequests(
                    level=LevelHistogramOptions(), issuer=IssuerHistogramOptions()
                ),
            )
        ),
    )
    histograms = first.histograms or Histograms()

    summaries: dict[str, Summary] = {}
    page: SearchFirstPage | SearchPage = first
    while True:
        for summary in page.summaries:
            summaries.setdefault(summary.id, summary)
        if page.next is None or len(summaries) >= MAX_DOCUMENTS:
            break
        page = client.continue_search(page.next)
    kept = list(summaries.values())[:MAX_DOCUMENTS]

    print(f"{title}: {len(kept)} documents")
    if len(kept) == MAX_DOCUMENTS < first.hits:
        print(
            f"{title}: the search has {first.hits} results, and MAX_DOCUMENTS keeps "
            f"{MAX_DOCUMENTS}. Narrow the search, or raise MAX_DOCUMENTS to get more.",
            file=sys.stderr,
        )
    elif page.truncated is not None:
        print(
            f"{title}: the search has {first.hits} results, and paging stopped before the end "
            f"({page.truncated.reason}). Narrow the search to get the rest.",
            file=sys.stderr,
        )
    return Sector(
        title=title,
        hits=first.hits,
        levels={bucket.level: bucket.hits for bucket in histograms.level or ()},
        provinces={
            bucket.issuer: bucket.hits
            for bucket in histograms.issuer or ()
            if bucket.issuer in PROVINCES
        },
        summaries=kept,
    )
```

## Details

A search result carries most of what the register needs, the link to the source page among
it, but the issuing department and the text itself are only in a document's detail. The
program asks for the detail of every document it found, 32 at a time, the most one request
takes. A document two sectors found is asked for once.

The register gives the length of the text rather than the text: a notice of a few hundred
characters and a plan of thirty thousand look alike in a list of headlines, and the length
tells you which to set an afternoon aside for. A document without running text, such as a
page of attachments, has no length.

Detail comes back in no particular order, so the answers are matched to the documents by
`id`. An id the API no longer knows comes back under `missing`; its rows are still written,
from the search result, with those two cells left empty.

```python
def details(client: Client, ids: list[str]) -> dict[str, Detail]:
    found: dict[str, Detail] = {}
    for start in range(0, len(ids), 32):
        result = client.get_details(ids[start : start + 32])
        for detail in result.detail:
            found[detail.id] = detail
        for id in result.missing:
            print(
                f"No detail for {id}: its rows have no department or length.",
                file=sys.stderr,
            )
    return found
```

## Provinces in English

The API names a province in Chinese, as its government does. The workbook shows the English
name from this table. A document's *Province* is its issuer when the issuer is a province,
and empty when it is a city, a county or a central body, as in the counts by province.

```python
PROVINCES = {
    "北京市": "Beijing",
    "天津市": "Tianjin",
    "河北省": "Hebei",
    "山西省": "Shanxi",
    "内蒙古自治区": "Inner Mongolia",
    "辽宁省": "Liaoning",
    "吉林省": "Jilin",
    "黑龙江省": "Heilongjiang",
    "上海市": "Shanghai",
    "江苏省": "Jiangsu",
    "浙江省": "Zhejiang",
    "安徽省": "Anhui",
    "福建省": "Fujian",
    "江西省": "Jiangxi",
    "山东省": "Shandong",
    "河南省": "Henan",
    "湖北省": "Hubei",
    "湖南省": "Hunan",
    "广东省": "Guangdong",
    "广西壮族自治区": "Guangxi",
    "海南省": "Hainan",
    "重庆市": "Chongqing",
    "四川省": "Sichuan",
    "贵州省": "Guizhou",
    "云南省": "Yunnan",
    "西藏自治区": "Tibet",
    "陕西省": "Shaanxi",
    "甘肃省": "Gansu",
    "青海省": "Qinghai",
    "宁夏回族自治区": "Ningxia",
    "新疆维吾尔自治区": "Xinjiang",
}


def province(issuer: str) -> str | None:
    return PROVINCES.get(issuer)
```

## Text stays text

Headlines and other fields come straight off the internet. openpyxl writes any text
beginning with `=` as a formula, which Excel would then run. We avoid this by marking
every cell as text. You see the same thing in the cell either way.

A cell holds at most 32,767 characters. A summary stays far below that. A document's full
text can exceed it, and belongs in a file of its own rather than in a cell.

```python
Value = str | int | date | None


def append(sheet: Worksheet, values: list[Value], bold: bool = False) -> None:
    sheet.append(values)
    for cell in sheet[sheet.max_row]:
        if isinstance(cell.value, str):
            cell.data_type = "s"
        if bold:
            cell.font = Font(bold=True)
```

## The documents sheet

One row per document and sector: a document two sectors found has a row in each. *Date* is a
date Excel can sort and filter. Every document has one, and *Date kind* beside it says which
of its dates it is: `published`, `issued`, `implemented`, or `added`, the day ReConnect China
collected it, which can be later than the document's own date. *Length* is the number of
characters in the Chinese text. *ReConnect China* is the link to the document on
reconnectchina.org, and it is how you cite it.

Your organization's agreement can leave out some fields of a document, such as its Chinese
text. A field left out is absent, and the document's `hidden` names it. Its cell stays empty,
as *Title (Chinese)* and *Length* do for a document whose Chinese text is left out.

The header row stays in view while you scroll, and every column can be filtered.

```python
COLUMNS = {
    "Sector": 24,
    "Title (English)": 48,
    "Title (Chinese)": 40,
    "Document number": 24,
    "Summary": 80,
    "Level": 10,
    "Province": 14,
    "Type": 20,
    "Issuer": 20,
    "Department": 24,
    "Date": 12,
    "Date kind": 11,
    "Length": 9,
    "Source": 40,
    "ReConnect China": 40,
    "Id": 16,
}
SUMMARY, SOURCE, RC = "Summary", "Source", "ReConnect China"


def row(sector: Sector, summary: Summary, detail: Detail | None) -> list[Value]:
    department = length = None
    if detail is not None:
        department = detail.department
        if detail.zh is not None and detail.zh.body is not None:
            length = sum(len(paragraph) for paragraph in detail.zh.body)
    headline = summary.zh.headline if summary.zh is not None else None
    return [
        sector.title,
        summary.en.title,
        "".join(headline) if headline is not None else None,
        summary.document_number,
        summary.en.summary,
        summary.level,
        province(summary.issuer),
        summary.type,
        summary.issuer,
        department,
        china_date(summary.date),
        summary.date_kind,
        length,
        summary.source,
        summary.rc,
        summary.id,
    ]


def documents(sheet: Worksheet, sectors: list[Sector], found: dict[str, Detail]) -> None:
    sheet.title = "Documents"
    append(sheet, list(COLUMNS), bold=True)
    for sector in sectors:
        for summary in sector.summaries:
            append(sheet, row(sector, summary, found.get(summary.id)))

    names = list(COLUMNS)
    for line in sheet.iter_rows(min_row=2):
        line[names.index(SUMMARY)].alignment = Alignment(wrap_text=True, vertical="top")
        for link in (line[names.index(SOURCE)], line[names.index(RC)]):
            if link.value:
                link.hyperlink = str(link.value)
                link.style = "Hyperlink"
    for number, width in enumerate(COLUMNS.values(), start=1):
        sheet.column_dimensions[get_column_letter(number)].width = width
    sheet.freeze_panes = "A2"
    sheet.auto_filter.ref = sheet.dimensions
```

## The counts sheet

Two tables. *By level* has a row per sector, with its number of documents and how many of them
were issued at each administrative level. *By province* has a row per province and a column
per sector, from the issuers that are provinces in the table of English names above. The last
row counts the other issuers: most central documents, and those whose province the classifier
has not found.

The sectors' counts add up to more than the documents there are, because a document can
belong to several sectors. That is why each sector is counted by its own search.

```python
LEVELS = ["centre", "provinces", "cities", "other"]


def labels(known: list[str], counts: list[dict[str, int]]) -> list[str]:
    """The labels in `known`, in their order, then any other the counts hold."""
    return known + sorted({label for count in counts for label in count} - set(known))


def counts(sheet: Worksheet, sectors: list[Sector]) -> None:
    sheet.title = "Counts"
    levels = labels(LEVELS, [sector.levels for sector in sectors])
    provinces = list(PROVINCES)

    append(sheet, ["By level"], bold=True)
    append(sheet, ["Sector", "Documents", *levels], bold=True)
    for sector in sectors:
        append(
            sheet,
            [sector.title, sector.hits, *(sector.levels.get(level, 0) for level in levels)],
        )
    append(sheet, [])
    append(sheet, ["By province"], bold=True)
    append(sheet, ["Province", *(sector.title for sector in sectors)], bold=True)
    for name in provinces:
        append(sheet, [province(name), *(sector.provinces.get(name, 0) for sector in sectors)])
    others = [sector.hits - sum(sector.provinces.values()) for sector in sectors]
    append(sheet, ["Other issuers", *others])
    sheet.column_dimensions["A"].width = 24
```

## Putting it together

The workbook is a new file every time; the program never opens yours to fill it in. openpyxl
cannot keep the charts and images of a workbook it opens and saves again, and a register with
dashboards would lose them. Copy the rows over into your own workbook, or link to this one.

```python
def main(client: Client) -> None:
    month = MONTH or last_month(datetime.now(CHINA).date())
    titles = find_searches(client)
    sectors = [run(client, name, title, month) for name, title in titles.items()]
    ids = list(dict.fromkeys(summary.id for s in sectors for summary in s.summaries))
    found = details(client, ids)

    workbook = Workbook()
    sheet = workbook.active
    assert sheet is not None
    documents(sheet, sectors, found)
    counts(workbook.create_sheet(), sectors)
    output = f"sectors-{month}.xlsx"
    workbook.save(output)
    print(f"{len(ids)} documents written to {output}")
```

## Logging in and running it

The program asks you to log in every time it runs: it prints a link, you open it and log in
with your reconnectchina.org account, and the login ends with the program. Nothing is saved,
so there is no secret to keep safe.

A program that runs again and again, or with nobody at the keyboard, can keep a login in a
file instead: see *Creating a token for a script* in the API documentation.

```python
if __name__ == "__main__":
    # The API is for partner organizations. To try the example on the sandbox, which every
    # account in an organization can use, pass server="https://sandbox.api.reconnectchina.org".
    client = Client(prompt=ConsolePrompt())
    main(client)
```
