0

我正在为 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();
                    }
                }
            }
        }
    }
4

1 回答 1

0

真正的解决方案是清理数据。尝试在返回数据的存储过程中执行此操作,我相信这是最好的方法。

如果这不可能,您可能希望在 CLR 程序集中执行此操作:使用 aSqlDataReader而不是SqlDataAdapter,清理每个检索到的值并逐个单元格地添加这些值。

于 2013-02-04T16:13:23.787 回答