Я создал новый документ Word на основе существующего документа Word в проекте надстройки Word Blazor. Я хочу добавить содержимое в новый документ Word, а также загрузить панель задач в новый документ Word, аналогичный существующей панели задач Word. Я написал код, но он не отображает содержимое в новом документе, он отображается в существующем текстовом контексте, а панель задач также не загружается автоматически в новом текстовом документе. По сути, я хочу создать текстовый документ, похожий на существующий текстовый документ.
export async function createNewDocument() {
try {
// Create and open the new document
let newDocUrl;
await Word.run(async (context) => {
const newDoc = context.application.createDocument();
newDoc.open();
// Sync to ensure the new document is opened
await context.sync();
// Get the URL of the new document (if possible, or use another method)
newDocUrl = Office.context.document.url; // This helps confirm we're dealing with the new doc
});
// Adding a short delay to ensure the new document is fully initialized
await new Promise(resolve => setTimeout(resolve, 1000));
// Use another `Word.run` block to interact with the new document explicitly
await Word.run(async (newContext) => {
// Ensure the context is correctly tied to the newly opened document
if (Office.context.document.url === newDocUrl) {
const newDocument = newContext.document;
// Insert content into the new document
newDocument.body.insertText(
"This is the new content for the new document.",
Word.InsertLocation.end
);
// Sync after content insertion
await newContext.sync();
// Set the task pane to auto-show with the new document
Office.context.document.settings.set(
'Office.AutoShowTaskpaneWithDocument',
true
);
// Save the settings asynchronously
await new Promise((resolve, reject) => {
Office.context.document.settings.saveAsync((result) => {
if (result.status === Office.AsyncResultStatus.Succeeded) {
resolve();
} else {
reject(result.error);
}
});
});
// Show the task pane explicitly in the new document
Office.addin.showAsTaskpane();
// Sync to confirm task pane is shown
await newContext.sync();
} else {
throw new Error("Failed to switch to the new document context.");
}
});
} catch (error) {
console.error("Error creating or modifying the new document: ", error);
// Detailed error logging
if (error instanceof OfficeExtension.Error) {
console.error("Debug info: ", JSON.stringify(error.debugInfo));
}
throw error; // Re-throw to handle in the calling function
}
}
Я успешно создал новый документ Word на основе существующего документа Word. Но я не могу добавить содержимое в новый документ Word и автоматически загрузить панель задач, поскольку она похожа на существующую панель задач Word. Я хочу автоматически загрузить боковой загрузчик в Word. Мое условие: существующий документ уже сохранен и содержит контент, необходимый мне для создания нового документа и вставки моего контента или данных в новый документ Word, а также загрузки панели задач (боковой загрузчик) так же, как существующий документ Word? мой код С# ниже
private async Task EditDocument()
{
try
{
isDocumentSaved = await JSRuntime.InvokeAsync("wordInterop.checkIfDocumentIsSaved");
Console.WriteLine("status of saved docuemnt"+ isDocumentSaved);
if (isDocumentSaved == true)
{
try
{
// Create a new document and ensure all operations are in its context
await JSModule.InvokeVoidAsync("createNewDocument");
return "New document created and operations performed.";
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
throw new Exception("Error in processing new document: " + ex.Message);
}
}
else
{
//perform ooperation in existing word document
}
}
catch (Exception ex)
{
throw new Exception("message:-"+ ex.Message);
}
}
Подробнее здесь: https://stackoverflow.com/questions/790 ... d-document
Автоматически загружать панель задач во вновь созданном документе Word из существующего документа Word в проекте Word, д ⇐ C#
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение
-
-
Как предотвратить срабатывание onItemSelected на вновь созданном экземпляре Spinner?
Anonymous » » в форуме Android - 0 Ответы
- 39 Просмотры
-
Последнее сообщение Anonymous
-