我正在Microsoft Visual Studio中编写一个c#WinForms应用程序。我们的数据团队以.csv格式向我提供每日报告,并且需要以可视方式显示结果。但是,这个程序最初是为了处理.xlsx文件而编写的,所以我没有重写所有的代码来处理.csv文件,而是决定将文件转换为.xlsx会比较容易,然后将剩下的代码保留原样。c#Excel Interop _Workbooks.Open
因此,我修改了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。 –
*该文件无法打开,因为找不到它。*这是不言而喻的 –