C# 无法将文本框数据保存到 excel 文档

C# Cannot save textbox data to excel document

据我所知,以下代码没有错误可言:

    private Excel.Application Xls;
    private Excel.Workbooks XlsB;
    private Excel.Workbook WB;
    private Excel.Worksheet WS;
    private Excel.Sheets WBs;

private void btnPrint_Click(object sender, EventArgs e)
    {
        try
        {
            Xls = new Excel.Application();
            XlsB = Xls.Workbooks;
            WB = XlsB.Open(lblPath.Text, 0, false, 5, "", "", true,
                XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
            Sheets WBs = WB.Worksheets;
            Worksheet WS = WBs.get_Item(1);
            WS.Cells[1, 1] = txtTATW.Text;
            WB.Save();
        }
        catch (Exception ex)
        {
            MessageBox.Show("Write Excel: " + ex.Message);
        }
        finally
        {
            GC.Collect();
            GC.WaitForPendingFinalizers();
            releaseObject(WS);
            releaseObject(WBs);
            releaseObject(WB);
            releaseObject(XlsB);
            WB.Close(true, lblPath.Text, misValue);
            Xls.Quit();
            releaseObject(Xls);
        }
    }

最后发布方法:

        private void releaseObject(object obj)
    {
        try
        {
            System.Runtime.InteropServices.Marshal.FinalReleaseComObject(obj);
            obj = null;
        }
        catch (Exception ex)
        {
            obj = null;
            MessageBox.Show("Unable to release the Object " + ex.ToString());
        }

    }

一些数据是从不同的表格中转移过来的,这里看不到,但是所有重要的都应该列出来!

它基本上只是将数据从文本框中提取到特定的单元格中。现在,我只用一次细胞测试它。 在此希望第二双眼睛可以帮助我找到解决方案。

我在发布之前移动了行 ~WB.Close()~ ~releaseObject(WB)~ 代码用一些文本更改了单元格 [1,1]。我更改了表单中的路径和文本,但 excel 部分保存正确。希望这有帮助。

private Excel.Application Xls;
private Excel.Workbooks XlsB;
private Excel.Workbook WB;
private Excel.Worksheet WS;
private Excel.Sheets WBs;
string lblPath = "SomePath";
string txtTATW = "Some Text";

private void btnPrint_Click(object sender, EventArgs e)
{
  try
  {
    Xls = new Excel.Application();
    XlsB = Xls.Workbooks;
    WB = XlsB.Open(@"H:\ExcelTestFolder\TestAddData.xlsx", 0, false, 5, "", "", true,
        XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
    WBs = WB.Worksheets;
    WS = WBs.get_Item(1);
    WS.Cells[1, 1] = txtTATW;
    WB.Save();
  }
  catch (Exception ex)
  {
    MessageBox.Show("Write Excel: " + ex.Message);
  }
  finally
  {
    GC.Collect();
    GC.WaitForPendingFinalizers();
    WB.Close();
    Xls.Quit();
    releaseObject(WS);
    releaseObject(WBs);
    releaseObject(WB);
    releaseObject(XlsB);
    releaseObject(Xls);
  }
  MessageBox.Show("Finished Updating File");
}