2014-11-05 85 views
0

我正在製作Windows應用商店應用,並且希望允許按下「導出到Word」按鈕的用戶將所有已輸入到應用中的數據顯示在Word文檔中並保存到計算機上的所需位置。下面的代碼是幾乎完成我所追求的代碼的一段測試,但是在保存文檔並使用Word而不是應用程序打開它之後,它無法打開文件,因爲它顯然已被損壞。但是,當您在記事本中打開它時,文本將顯示爲我想要的。在Windows應用商店應用中使用FilePicker保存自定義Word文檔

private async void exportToWord_Click(object sender, RoutedEventArgs e) 
{ 
    await ExportToWord(); 
} 

private async Task ExportToWord() 
{ 
    // Create the picker object and set options 
    Windows.Storage.Pickers.FileSavePicker savePicker = new Windows.Storage.Pickers.FileSavePicker(); 

    savePicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary; 

    // Dropdown of file types the user can save the file as 
    savePicker.FileTypeChoices.Add("Word", newList<string>{".docx"}); 

    // Default file name if the user does not type one in or select a file to replace 
    savePicker.SuggestedFileName = "Test"; 

    Windows.Storage.StorageFile file = await savePicker.PickSaveFileAsync(); 

    MessageDialog mD; 

    if (file != null) 
    { 
     // Prevent updates to the remote version of the file until we finish 
     // making changes and call CompleteUpdatesAsync. 
     Windows.Storage.CachedFileManager.DeferUpdates(file); 

     // write to file 
     await Windows.Storage.FileIO.WriteTextAsync(file, createContentsOfFile()); 

     // Let Windows know that we're finished changing the file so the other 
     // app can update the remote version of the file. 
     // Completing updates may require Windows to ask for user input. 
     Windows.Storage.Provider.FileUpdateStatus updateStatus = await Windows.Storage.CachedFileManager.CompleteUpdatesAsync(file); 

     if (updateStatus == Windows.Storage.Provider.FileUpdateStatus.Complete) 
     { 
      mD = newMessageDialog("Connect exported to:" + file, "Export Successful"); 
     } 
     else 
     { 
      mD = newMessageDialog("Could not save file. Try again", "Export Unsuccessful"); 
     } 
    } 
    else 
    { 
     mD = newMessageDialog("Operation canceled because the file could not be found. Try again", "Export Unsuccessful"); 
    } 

    await mD.ShowAsync(); 
} 

private string createContentsOfFile() 
{ 
    return "Testing..."; 
} 

我相信這個問題是我輸出純文本到Word文檔,但它需要在一定的格式正確地輸出並顯示在一個Word文檔。有什麼方法可以在Windows Store應用程序中執行此操作?

任何幫助,將不勝感激。

回答

0

我不知道任何可用於Windows運行時應用程序的Word文檔組件(Microsoft不提供一個,但可能有我不知道的第三方組件)。

您可以獲得documentation on the docx格式,對於簡單文本,它可能不會太複雜(我不確定),或者您可以使用Word可以打開的另一種格式。

如果你不需要格式化,我可能會堅持使用txt。

如果您需要少量格式化,那麼rtf是一個不錯的選擇。生成自己的文件相當簡單,或者RichEditBox可以導出RTF格式的文本,然後將其保存到.doc文件並在Word中打開。

相關問題