[英]Convert Microsoft.Office.Interop.Excel.Application to byte[]
I am creating a excel file in the code as Shown Below 我正在代码中创建一个excel文件,如下所示
Microsoft.Office.Interop.Excel.Application excelFile = CreateExcelFile();
now I want to convert this excelFile to byte[] without saving to hard drive. 现在我想将此excelFile转换为byte []而不保存到硬盘驱动器。 How is it possible?
这怎么可能?
had the same problem some time ago. 前段时间有同样的问题。 You have to create a temporary file, and then read it to a byte array.
您必须创建一个临时文件,然后将其读取为字节数组。
Example code: 示例代码:
string tempPath = AppDomain.CurrentDomain.BaseDirectory + DateTime.Now.Hour + DateTime.Now.Minute + DateTime.Now.Second + DateTime.Now.Millisecond + "_temp";//date time added to be sure there are no name conflicts
workbook.SaveAs(tempPath, workbook.FileFormat);//create temporary file from the workbook
tempPath = workbook.FullName;//name of the file with path and extension
workbook.Close();
byte[] result = File.ReadAllBytes(tempPath);//change to byte[]
File.Delete(tempPath);//delete temporary file
That isn't an Excel File
it is a COM object used for Excel Automation. 这不是
Excel File
它是用于Excel Automation的COM对象。 It can be used to request Excel to save a document to disk (as a temporary file), which you could then load into a byte[]
and then delete the temporary file. 它可以用于请求Excel将文档保存到磁盘(作为临时文件),然后可以将其加载到
byte[]
,然后删除临时文件。
The following code could be used to do this for the active workbook: 以下代码可用于为活动工作簿执行此操作:
public byte[] GetActiveWorkbook(Microsoft.Office.Interop.Excel.Application app)
{
string path = Path.GetTempFileName();
try
{
app.ActiveWorkbook.SaveCopyAs(path);
return File.ReadAllBytes(path);
}
finally
{
if(File.Exists(path))
File.Delete(path);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.