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

时间:2016-11-24 05:52:22

标签: c# excel interop oledb excel-interop

据我所知,以下代码中没有任何错误可以解释:

    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());
        }

    }

某些数据是从另一种形式转移而来的,这在此处不可见,但应列出所有重要内容!

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

1 个答案:

答案 0 :(得分:0)

我在发布之前移动了行~WB.Close()〜释放对象(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");
}