如何提示用户保存自动Excel文件

本文关键字:保存 Excel 文件 用户 何提示 提示 | 更新日期: 2023-09-27 18:25:18

我已经搜索过了,但没有任何内容直接命中我要查找的内容(或者我的搜索没有命中单词组合)。

在C#中,我使用Interop.Excel创建了一个Excel工作表,在其中插入一些数据并创建一个图表。当我做xlWorkBook.SaveAs.时,这一切都很好

我想做的是提示用户将自动工作簿放在有自己文件名的地方。我试过了(http://p2p.wrox.com/vb-how/63900-disabling-second-excel-save-prompt.html)他基本上做了一个新的SaveFileDialog,如果它==OK,他会构建他的Excel表,然后他会说这是他的工作簿。另存为(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

如何提示用户保存自动Excel文件

这是一种简单的方法。:-)

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;
        }