【发布时间】:2015-10-06 05:41:00
【问题描述】:
我正在 Microsoft Visual Studio 中编写一个 c# WinForms 应用程序。我们的数据团队正在给我一份 .csv 格式的每日报告,我需要直观地显示结果。但是,这个程序最初是为处理 .xlsx 文件而编写的,因此我决定将文件转换为 .xlsx 然后将其余代码保持原样,而不是重写我的所有代码来处理 .csv .
因此,我修改了 drawCharts() 方法的第一部分,该方法负责从 xlsx 收集信息并将其呈现为 excel 图表。
我的研究向我展示了两种将外部文件读入 Excel 工作簿的方法,第一种使用 Workbooks.Open,第二种使用 Workbooks.OpenText。
这是我的代码:
private void drawCharts()
{
//Declare variables for use
//These first three values are going to be used later and can be ignored.
Excel.Application xlApp = null;
Excel.Workbook xlWorkbook = null;
Excel.Worksheet xlWorksheet = null;
object misValue = System.Reflection.Missing.Value;
string path = "\\\\Data\\Departmental Data\\TechSupport\\_Report"
//define the actual file path. Separate because I use the path variable elsewhere
string source = Path.Combine(path, "report.csv");
//define the destination file. Using Environment.UserName so multiple people can run this program at the same time, all using unique files except when they first load. There's probably a better way of doing this.
string use = Path.Combine(path, "Report-" + Environment.UserName + ".xlsx");
//A boolean telling the program to exit if there was an error
bool shouldExit = false;
Excel.Application app = null; //Temporary application used for opening the csv
try
{
MessageBox.Show("Opening file " + source);
app = new Excel.Application();
Excel.Workbook wb = app.Workbooks.Open(source); //source points to the csv. This is the line that fails.
MessageBox.Show(String.Format("Saving {0} as {1}", source, use));
wb.SaveAs(use, Excel.XlFileFormat.xlOpenXMLWorkbook);
wb.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
shouldExit = true;
}
finally
{
if (app != null) { app.Quit(); }
releaseObject(app);
if (shouldExit) { Environment.Exit(1); }
}
//Rest of the code...
}
违规行是Excel.Workbook wb = app.Workbooks.Open(source);。执行此行时,Excel 会引发错误,指出无法打开该文件,因为找不到该文件。研究这个,我发现this article 说我应该把它改成Excel.Workbook wb = app.Workbooks.OpenText(source)。但是,这只会导致编译器错误指出Cannot implicitly convert type 'void' to 'Microsoft.Office.Interop.Excel.Workbook'。
任何想法都将不胜感激。
【问题讨论】:
-
为什么不编写代码来处理 .csv?这些是一些最容易使用的文件(假设它们设置良好)。
-
这样也行。不幸的是,我遇到了另一个问题。其中一个字段是其中包含文本名称的列,因此我得到
business, Inc.,它当然会变为两列而不是保持为一列。我将不得不与我们的数据团队交谈,看看他们是否可以在此列周围添加双引号,或者(对我来说更容易)是否可以导出为 .xlsx。 -
无法打开该文件,因为它找不到。这很不言自明