我编写了一个小型应用程序,它从 PLC 收集数据,然后将该数据写入 Excel。当我第一次打开应用程序收集数据时,它工作得很好,但是,如果我尝试再次收集,它不会将任何数据放入文件中,而只是在模板文件上另存为。如果我重新启动应用程序,它会再次工作,但只有 1 次。这是简化的代码。
// Open the Excel application
Excel.Application excel = new Excel.Application();
// Open the workbook
string filelocation = Properties.Settings.Default.templateLocation;
Excel.Workbook workbook = excel.Workbooks.Open(filelocation);
//Define the worksheet and open
Excel.Worksheet sh = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Sheets["MULTIPLE_SHOT_DATA"];
//Saves as dialog control to get filename and location
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
if (Properties.Settings.Default.filedir != null || Properties.Settings.Default.filedir != "")
{
saveFileDialog1.InitialDirectory = Properties.Settings.Default.filedir;
}
saveFileDialog1.Filter = "Worksheet (*.xlsx)|*.xlsx|All Files (*.*)|*.*";
saveFileDialog1.Title = "Save an Excel File";
saveFileDialog1.ShowDialog();
//Column loop should be 24 or 36 for different ball machines
for (int columnloop = 0; columnloop < 24; columnloop++)
{
int inbounddata = columnloop;
string inbounddatastring = inbounddata.ToString();
_myItem.HWTagType = TagType.AUTO;
_myItem.HWTagName = "Ball[" + inbounddatastring + ",0]";
_myItem.Elements = 100;
try
{
// Call Item.Read method
_myItem.Read();
// For atomic types, each Item.Values element represents one atomic value.
if (!_myItem.Values[0].GetType().IsArray)
{
for (int i = 0; i < _myItem.Elements; i++)
{
int inboundcolumn = excelcolumn;
fint = i + 1;
sh.Cells[fint, inboundcolumn] = _myItem.Values[i];
}
}
// For structured types (UDT, PDT, and System), each Item.Values element represents an array of bytes
else
{
}
}
catch (Exception ex)
{
AddEvent("Error, Item.Quality is " + _myItem.Quality.ToString();
}
finally
{
this.Cursor = Cursors.Default;
}
}
}
//Save as and close active file
workbook.SaveAs(@Properties.Settings.Default.filename, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, XlSaveAsAccessMode.xlNoChange,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
Marshal.FinalReleaseComObject(sh);
workbook.Close();
Marshal.FinalReleaseComObject(workbook);
// Quit the Excel application
excel.Quit();
Marshal.FinalReleaseComObject(excel);
我希望这会多次起作用,但事实并非如此。
我认为您可能已将此代码放入已加载或开始事件中。为什么不创建一个按钮并向其中添加此代码呢?据我所知,它运行一次的原因是因为该代码位于被触发一次的事件中。