簡體   English   中英

如何提示用戶保存自動Excel文件

[英]How to prompt user to save an automated Excel file

我已經搜索過,而且我發現沒有任何內容可以直接點擊我正在尋找的東西(或者我的搜索沒有找到單詞的組合)。

在C#中,我使用Interop.Excel創建了Excel工作表,在其中插入了一些數據並創建了一個圖表。 當我執行xlWorkBook.SaveAs時,這一切都正常。

我想要做的是提示用戶將自動化工作簿放在他自己的文件名的某個地方。 我試過( http://p2p.wrox.com/vb-how/63900-disabling-second-excel-save-prompt.html )他基本上做了一個新的SaveFileDialog然后如果它==確定他建立了他的Excel表格然后他說他的工作簿.SaveAs(FilePathFromSaveAsDialog)會導致提示。 當我嘗試它時,我得到“顯示模式對話框,當應用程序未在UserInteractive模式下運行不是一個有效的操作”錯誤。 我會粘貼我的所有代碼,但它是在一個單獨的系統上,但它的正好是:

using Excel = Microsoft.Office.Interop.Office 

//....then on click of link button....

Excel.Application xlApp;
Excel.Workbook xlWorbook;
Excel.Workbooks xlWorkbooks;
Excel.Sheets xlSheets;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;

xlApp = new Excel.ApplicationClass();
xlWorkBooks = xlApp.Workbooks;
xlWorkBook = xlWorbooks.Add(misValue);
xlSheets = xlWorkBook.Worksheets;
xlWorkSheet = (Excel.Worksheet)xlSheets.get_Item(1);

//....Now I fill my Excel sheet data and make my chart >>> then I close like below...

xlApp.DisplayAlerts = true;

//HERE IS WHERE I WANT TO EITHER PASS THE PATH AND FILE NAME FROM USER OR USE A PROMPT
xlWorkBook.SaveAs("Test.xls", Excel.XFileFormat.XlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);    
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();

//finally I release all my objects via Marshal.ReleaseComObject then GC.Collect

這是簡單的方法。 :-)

myFilename = xlapp.GetSaveAsFilename
xlWorkbook.SaveAs filename:=myFilename

如果您在保存后將文件存儲在某處,則可以使用Response。

這是一個例子:

  const string fName = @"C:\Test.xls";
  FileInfo fi = new FileInfo(fName);
  long sz = fi.Length;

  Response.ClearContent();
  Response.ContentType = Path.GetExtension(fName);
  Response.AddHeader("Content-Disposition", string.Format("attachment; filename = {0}",System.IO.Path.GetFileName(fName)));
  Response.AddHeader("Content-Length", sz.ToString("F0"));
  Response.TransmitFile(fName);
  Response.End();

這應該提示用戶他們想要將文件存儲在他們的機器上。

這就是我做的,看起來很瘋狂,但很有效。

xlWorkBook.SaveAs(saveExcel(), Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);//import method

internal object saveExcel()//method

    {

        SaveFileDialog sfd = new SaveFileDialog();// Create save the CSV
        sfd.Filter = "Text File|*.xls";// filters for text files only
        sfd.DefaultExt = "xls";
        sfd.AddExtension = true;
        sfd.FileName = "AutodeskScripts.xls";
        sfd.Title = "Save Excel File";
        if (sfd.ShowDialog() == DialogResult.OK)
        {
            return sfd.FileName;
        }
        else
        {
            return null;
        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM