ExcelPackage.Dispose()阻止从串行端口

时间:2018-08-17 18:37:31

标签: c# epplus

我的应用程序需要打开一个串行端口并等待数据传输。打开串行端口后,我使用EPPlus从excel表中读取数据并将其存储在词典列表中。

但是,当我添加Read方法时,我停止从串行端口接收数据。经过一些测试,当我用来读取Excel工作表的ExcelPackage上调用.Dispose()时,串行端口似乎断开。

我的Excel读取代码如下:

public List<Dictionary<string, string>> Read(string fileName)
    {
        List<Dictionary<string, string>> dictList = new List<Dictionary<string, string>>();
        FileInfo file = Utils.GetFileInfo(fileName, false);

        // using statement automatically calls Dispose() which closes the package.
        using (ExcelPackage package = new ExcelPackage(file))
        {
            // Reads the first worksheet of the workbook
            ExcelWorksheet worksheet = package.Workbook.Worksheets[1];
            int endColumn = worksheet.Dimension.End.Column;
            int endRow = worksheet.Dimension.End.Row;

            // Start loop from 2nd row to avoid headers
            for (int row = 2; row <= endRow; row++)
            {
                Dictionary<string, string> dictionary = new Dictionary<string, string>();

                for (int column = 1; column <= endColumn; column++)
                {
                    // Add key value pair to dict for every column
                    // key = column header
                    // value = cell value to string

                    // key is set to "" if cell is empty
                    string key = worksheet.Cells[1, column].Value == null ? "" : worksheet.Cells[1, column].Value.ToString();
                    // value is set to "" if cell is empty
                    string value = worksheet.Cells[row, column].Value == null ? "" : worksheet.Cells[row, column].Value.ToString();

                    dictionary.Add(key, value);
                }
                dictList.Add(dictionary);
            }
        }
        return dictList;
    }

我的串行端口在另一个类中打开:

public BarcodeScanner()
    {
        try
        {
            SerialPort mySerialPort = new SerialPort(SearchComPort());
            mySerialPort.Open();
            mySerialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
            isAvailable = true;
        }

        catch (Exception ex)
        {
            Debug.WriteLine("Error: {0}", ex.Message);
        }
    }

如果我使用该代码,似乎可以正常工作

ExcelPackage package = new ExcelPackage(file)

最后省略.Dispose()调用,但是根据我的理解,这将引起问题,因为它会使Excel工作表无法用于其他进程。

1 个答案:

答案 0 :(得分:0)

如果您使用System.IO.File.ReadAllBytes(fileName)将所有数据读入字节数组,将其放入流中,然后使用EPPlus的ExcelPackage的(流)重载之一打开excel文件,该怎么办?