我正在为 sql server 创建 CLR 程序集,它将一些数据从数据库保存到 excel 文件中。在我从数据库中收到无效字符错误之前,它可以正常工作:
System.ArgumentException:'',十六进制值 0x04,是无效字符。
问题是文件保持锁定状态,直到下次执行此 CLR 过程才能删除它。发生错误甚至删除文件时如何解锁文件?
另一个问题?我可以保存无效字符的excel文件吗?
using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
using ClosedXML.Excel;
[System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Assert, Name = "FullTrust")]
public partial class StoredProcedures
{
[Microsoft.SqlServer.Server.SqlProcedure]
public static void createExcel(SqlString procName, SqlString fileName, SqlString filePath, SqlXml xmlParams, out SqlBoolean result)
{
result = false;
DataSet exportData = new DataSet();
if (procName.Value == string.Empty)
throw new Exception("Procedure name value is missing.");
if (filePath.Value == string.Empty)
throw new Exception("Missing file path location.");
if (fileName.Value == string.Empty)
throw new Exception("Missing name of file.");
using (SqlConnection conn = new SqlConnection("context connection=true"))
{
using (SqlCommand getOutput = new SqlCommand())
{
getOutput.CommandText = procName.ToString(); ;
getOutput.CommandType = CommandType.StoredProcedure;
getOutput.CommandTimeout = 300;
getOutput.Connection = conn;
conn.Open();
using (SqlDataAdapter da = new SqlDataAdapter(getOutput))
{
da.AcceptChangesDuringFill = false;//drugače da pokliče na koncu AcceptChanges in hasChanges je vedno false
da.Fill(exportData);
conn.Close();
da.Dispose();
try
{
if (exportData.HasChanges())
{
using (XLWorkbook xlWb = new XLWorkbook(XLEventTracking.Disabled))
{
xlWb.Worksheets.Add(exportData.Tables[0]);
xlWb.SaveAs(filePath.ToString() + fileName.ToString());
result = true;
}
}
}
finally
{
exportData.Dispose();
}
}
}
}
}