【问题标题】:use filename ref instead of path(string) while opening an Excel in Windows c#在 Windows c# 中打开 Excel 时使用文件名引用而不是路径(字符串)
【发布时间】:2013-09-05 06:52:43
【问题描述】:

在 C# 中打开或保存 Excel 时,我需要传递文件名 ref 而不是给出字符串(完整路径)。下面是一段代码sn-p

object fileName = (string)e.Argument;

object oMissing = System.Reflection.Missing.Value;

if (fileName.ToString().EndsWith("xlsx"))
{
    Excel.Workbook wb;
    object oMissing1 = Type.Missing;
    var app = new Microsoft.Office.Interop.Excel.Application();
    wb = app.Workbooks.Open(@"C:\Users\273714\Desktop\ProoferReport1.xlsx", 
                            oMissing1, oMissing1, oMissing1, oMissing1, 
                            oMissing1, oMissing1, oMissing1, oMissing1, 
                            oMissing1, oMissing1, oMissing1, oMissing1, 
                            oMissing1, oMissing1);
    wb.SaveAs(@"C:\Users\273714\Desktop\Proofer Report2.xls", 
                            Excel.XlFileFormat.xlExcel8, Type.Missing, 
                            Type.Missing, Type.Missing, Type.Missing, 
                            Excel.XlSaveAsAccessMode.xlExclusive, 
                            Type.Missing, Type.Missing, Type.Missing, 
                            Type.Missing, Type.Missing);
    app.Quit();
    app.Quit();
}

如果是word文档,我可以直接打开它

oDoc = oWord.Documents.Open(ref fileName, ref oMissing,
               ref readOnly, ref oMissing, ref oMissing, ref oMissing,
               ref oMissing, ref oMissing, ref oMissing, ref oMissing,
               ref oMissing, ref isVisible, ref oMissing, ref oMissing,
               ref oMissing, ref oMissing);

我也需要在 Excel 中使用相同的文件名方式。任何帮助将不胜感激。

【问题讨论】:

  • 不确定您的问题究竟是什么意思。您想使用传递filename.xlsx 而不是C:\filename.xlsx
  • 我想在浏览文件并打开它时传递对象文件名而不是字符串。文件名不断变化。我不想硬编码它
  • 你有fileName对象中文件的完整路径吗?
  • 所以只需使用文件打开对话框,让用户选择文件,检查文件是否正确,然后显示另存为对话框供用户再次保存.....
  • 我很困惑..你为什么不能只使用fileName 变量? (或只是File.Copy

标签: c# excel ms-word ref


【解决方案1】:

如果我理解正确,您只想传递变量 FileName 而不是传递常量字符串“c:\aFilename.xlsx”?

为此,将object filename 替换为string filename,然后输入ref filename 而不是ref @"c:\aFilename.xlsx"

还要注意 System.IO.FileInfo 类 - 而不是 fileName.ToString().EndsWith("xlsx") 你可以使用 Path.GetExtension(filename).Equals("xlsx",StringComparison.InvariantCultureIgnoreCase) 来利用内置函数来查找文件扩展名(这也避免(例如)filename.abcxlsx 传递测试)。

【讨论】:

  • Path.GetExtension(fileName) 是一个更好的选择(虽然我不知道如果这回答了这个问题,问题的真正含义是什么)
  • 好点@Sayse - 我使用System.IO.FileInfo 因为最初我将文件名卡在那里,然后意识到因为它作为引用传递它会更好地将它存储在一个字符串中变量,因此可以返回一个值,但此时停止思考。现在更新答案。谢谢。
猜你喜欢
  • 2012-04-04
  • 2015-07-24
  • 2011-09-13
  • 2016-07-23
  • 1970-01-01
  • 1970-01-01
  • 2019-02-14
  • 1970-01-01
  • 2017-09-05
相关资源
最近更新 更多