Skip to Content
TAdminConfiguration workbooks and preview sessions

Configuration workbooks and preview sessions

On this page

AdminConfigurationWorkbookController imports and exports users, roles, menus and grants. The server validates the XLSX and freezes a candidate for paged review and confirmation. Preview does not write to the database.

See TExcel for file I/O and the validation and persistence example for custom data imports.

Choose the business command

Use these exact kind names. Each command has its own schema and authorization requirements.

kindData worksheetsWrite behavior
NewUsersUsers, UserRolesCreate local users and assign initial roles; import only, with no credential export
UserProfilesUsersUpdate existing usernames, display names, email and avatars, without changing passwords or login switches
UserRolesUsers, UserRolesReplace the complete role set of each user declared in the main sheet
RolesRolesAdd or update the basic details of non-system roles
MenusMenus, Buttons, MenuLocalesSave menus, buttons and menu translations under the normal editor and trusted-route rules
RolePermissionsRoles, MenuPermissions, ButtonPermissions, ApiPermissionsReplace declared roles’ complete menu, button and API permission sets with version checks

For example, declaring user 101 in UserRoles.Users with no corresponding detail rows clears that user’s roles. Users absent from the main sheet retain their assignments. Empty permission detail sets likewise clear the corresponding grants of a declared role. Absence from a detail sheet does not universally mean “leave unchanged.”

Workbook structure and fields

Every file requires Metadata and all data worksheets for its command. Retain complete headers even in empty detail sheets. Metadata has kind and version columns with exactly one data row: version text 1 and a kind matching the request. Guide is optional, and a hidden _TExcelEnums sheet is allowed. Duplicate names and other extra sheets are rejected.

The table lists stable field keys. Current exports can use the corresponding Chinese captions. Import binds the keys or their shared caption mapping; retain every column and do not substitute arbitrary aliases.

Command / worksheetComplete field keys
NewUsers / Userskey, userName, displayName, email, initialPassword, isEnabled, passwordLoginEnabled, mustChangePassword
NewUsers / UserRolesuserKey, roleId
UserProfiles / Usersid, userName, displayName, email, avatarUrl
UserRoles / UsersuserId
UserRoles / UserRolesuserId, roleId
Roles / Rolesid, roleName, roleCode, description, isEnabled, sort
Menus / Menuskey, id, parentKey, menuName, menuCode, module, path, menuType, componentKey, redirect, visible, keepAlive, openMode, externalUrl, icon, sort, isEnabled, isSystem, description, remark
Menus / Buttonsid, menuKey, buttonName, buttonCode, sort, isEnabled
Menus / MenuLocalesmenuKey, locale, localizedName
RolePermissions / RolesroleId, expectedPermissionVersion
RolePermissions / MenuPermissionsroleId, menuId
RolePermissions / ButtonPermissionsroleId, buttonId
RolePermissions / ApiPermissionsroleId, apiCode

Store IDs as positive decimal integer text to preserve long identifiers in Excel. Only ID columns that permit creation may be blank, such as Roles.id, Menus.id and Buttons.id; 0 is not a creation marker. Use true / false for booleans and current enum names for enums. Numeric enums and localized yes/no words are unsupported. Formulas, error cells and numeric values beyond reliable precision produce diagnostics.

NewUsers.key and Menus.key identify objects within the file. Their relationship fields, including userKey, menuKey and parentKey, resolve those keys according to each relationship. Do not infer relationships from row positions. Initial passwords follow the normal password policy and are excluded from public differences and error echoes. Preserve the exported RolePermissions.expectedPermissionVersion. API codes must exist in the current host’s actual permission catalog; duplicate detection is case-insensitive.

Generate a minimal role file

Run this complete program in a .NET 10 console project with TExcel installed. It creates Roles.xlsx containing one new role. Valid structure still requires domain checks for permissions and unique role codes. Reimporting does not automatically turn creation into an update by roleCode; updating an existing role requires its id.

using TExcel; using (var writer = Excel.CreateWriter("Roles.xlsx")) { writer.WriteSheet(new[] { new { kind = "Roles", version = "1" } }, "Metadata"); writer.WriteSheet(new[] { new { id = "", roleName = "Operators", roleCode = "OPS", description = "Import demo", isEnabled = "true", sort = "10" } }, "Roles"); writer.Complete(); } Console.WriteLine($"Sheets: {string.Join(", ", Excel.GetSheets("Roles.xlsx").Select(sheet => sheet.Name))}"); Console.WriteLine($"Role rows: {Excel.QueryAsDictionary("Roles.xlsx", sheetName: "Roles").Count()}");

Expected output:

Sheets: Metadata, Roles Role rows: 1

For existing configuration, prefer an export from the current host to retain real IDs, versions and referenceable resources. The export input selects a command with kind, a selection with nonempty ids, a menu module with module, and an instruction language with language (default zh-CN). Both objects and relationship rows count toward the export budget; narrow the selection when it exceeds the limit.

HTTP transport contract

Every action uses POST under /api/adminconfigurationworkbookcontroller/, with the host’s normal authentication and administration realm context.

ActionRequest bodySuccessful response
preview?kind=Roles&fileName=Roles.xlsxRaw XLSX bytes; URL-encode the filenamePreview object inside the host’s unified result envelope
readSession JSONCurrent change and diagnostic pages with full counts
commitThe same session JSONCommit stages and the current page
releaseThe same session JSONResult of releasing the owned candidate
exportExport-condition JSONXLSX bytes; this action uses SkipUnifyResult

For upload, Content-Type can be application/vnd.openxmlformats-officedocument.spreadsheetml.sheet. Send file bytes directly, without JSON.stringify(File) or multipart encoding. The host request adapter must recognize File / Blob and serialize ordinary DTOs as JSON. The download adapter must distinguish successful files from JSON errors. See Vue integration for envelope decoding and error propagation.

Use this JSON for read, commit and release, replacing sessionId with the preview’s value and retaining its returned revision:

{ "kind": "Roles", "sessionId": "<preview.sessionId>", "revision": 1, "page": 1, "sheet": "", "action": "" }

The candidate revision is fixed at 1; clients cannot edit the plan. A different file requires a new preview. Custom frontends use the HTTP APIs above.

Paging and complete error state

page is one-based. An empty sheet selects all sheets; action is empty or added, updated, unchanged. Changes filter by sheet and action; diagnostics filter only by sheet. Each page contains at most 50 changes and 50 diagnostics. The server normalizes the page number using the larger page count.

FieldMeaning
totalRows / filteredRowsAll / filtered public object changes, rather than physical XLSX rows or all relationship rows
addedCount / updatedCount / unchangedCountObject action counts across the complete candidate
retainedCountObjects outside the file that are retained
errorCount / filteredErrorsAll collected / sheet-filtered diagnostics, including early-stop markers
rows / diagnosticsCurrent pages, which do not represent the complete candidate or diagnostic set
canApplyerrorCount == 0 && totalRows > 0; eligibility to confirm the candidate
databaseCommitted / publishedSuccessful database commit / completed post-commit cache and audit stages

Diagnostics use sheet, rowNumber, field and code. Confirmation uses complete counts. Paging limits response details; the server retains the full candidate.

Authorization and commit stages

The controller requires Auth.Me; the service also checks the actual command permissions:

CommandImport permissionsExport permission
NewUsersUser.AddUser; assignments also require User.SetRolesUnsupported
UserProfilesUser.UpdateUserUser.GetUsers
UserRolesUser.SetRolesUser.GetUsers
RolesRole.AddRole for creation, Role.UpdateRole for updates; mixed candidates require bothRole.GetRoles
MenusMenu.SaveMenu; button creation / updates also require Button.AddButton / Button.UpdateButtonMenu.GetMenuTree
RolePermissionsRole.SetPermissionsRole.GetRoleById

Preview, paging and confirmation recheck the relevant permissions. After acquiring the administration mutation lock inside the commit transaction, the service rechecks permissions, target and reference facts, and the permission catalog. Relevant changes during preparation or after preview require a new preview. The actor comes from authenticated context, never from the workbook or a request-supplied user ID.

Observed stateHost behavior
canApply=falseShow diagnostics and preview a corrected file
databaseCommitted=falseSuccessful commit has not been recorded; read the same session after a failed confirmation
databaseCommitted=true, published=falseData is saved; retain the session and retry the same commit to continue cache / audit work
published=trueDatabase and publication stages completed; refresh normal queries and release the candidate
Timeout or disconnected confirmationRead the original session before deciding; disconnection does not prove rollback

Retrying commit on the same live session skips completed database writes and continues unfinished publication. release only releases the candidate; it cannot undo a transaction already started or data already committed.

Session lifetime and resource budgets

Candidates live in the current service instance’s process. Ownership includes realm, scope, tenant and stable user ID; normal token rotation does not change it. Sessions expire after 30 idle minutes, with successful retrieval renewing that period. Each service instance permits at most 32 sessions. A new preview of the same kind under the same ownership replaces its predecessor.

In a multi-instance deployment, route later requests to the instance holding the candidate, or implement a shared mechanism with the full lifecycle contract. Restart, expiry or replacement makes the old session unavailable. Session retries are not permanent cross-process idempotency keys. If a session is lost with an uncertain confirmation outcome, reconcile normal data and audit records before starting another import.

The current configuration implementation limits a file to 512 MiB, objects and relationships to 100,000 data rows combined, and a cell to 32,767 characters. Raw inspection separately limits scanning to 200,000 rows, 5,000,000 cells and 10,000 format diagnostics, followed by a stop marker when that diagnostic budget is exceeded. Archive budgets apply independently. These are current source limits; proxy and host upload limits can be smaller. Custom application imports should set their own budgets; see upload validation.

Source locations: TAdmin/src/TAdmin/Controllers/AdminConfigurationWorkbookController.cs, Services/Workbooks/AdminConfigurationWorkbookService.cs, Services/Workbooks/AdminConfigurationWorkbookCodec.cs and Services/Excel/ExcelImportSessions.cs.