请参阅此代码。
string name = dt.Rows[0]["Name"].ToString();
byte[] documentBytes = (byte[])dt.Rows[0]["DocumentContent"];
int readBytes = 0;
//int index = 0;
readBytes = documentBytes.Length;
try
{
using (FileStream fs = new FileStream(name, FileMode.Create, FileAccess.Write, FileShare.Read))
{
fs.Write(documentBytes, 0, readBytes);
//System.Diagnostics.Process prc = new System.Diagnostics.Process();
//prc.StartInfo.FileName = fs.Name;
Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application();
app.Visible = false;
Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Open(fs.Name);
Microsoft.Office.Interop.Excel._Worksheet worksheet = (Excel.Worksheet)workbook.Sheets[1]; // Explicit cast is not required here
// lastRow = worksheet.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell).Row;
app.Visible = true;
fs.Flush();
fs.Close();
}
}
catch (Exception ex)
{
MessageBox.Show("You have clicked more than one time. File is already open.", "WorkFlow", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
我正在使用文件流打开excel文件。 Excel很好地显示出来。但我无法关闭文件流。它还附带一个小弹出窗口,显示“现在可用文件”#。如何摆脱它?我可以看到fs.Close()和Flush()在这里真的不起作用。请帮忙。
答案 0 :(得分:3)
当您仍然打开流时,您要求Excel打开该文件。鉴于您只是尝试向其写入字节,我只使用:
// This will close the file handle after writing the data
File.WriteAllBytes(name, documentBytes);
// Then you're fine to get Excel to open it
var app = new Microsoft.Office.Interop.Excel.Application();
app.Visible = false;
var workbook = app.Workbooks.Open(name);