如何将数据从C#传递到excel现有文件

时间:2016-04-24 17:44:14

标签: c# excel datatable

我想创建一个按钮,用于将数据从3个文本框传递到excel表,但我希望每次都使用相同的表,只需将数据添加到新行。每次我想添加一些东西,它都会创建一个新的excel文件。这是我的代码。

        Excel.Workbook xlWorkBook;
        Excel.Worksheet xlWorkSheet;
        object misValue = System.Reflection.Missing.Value;

        xlWorkBook = xlApp.Workbooks.Add(misValue);
        xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
        xlWorkSheet.Cells[1, 1] = "Book name";
        xlWorkSheet.Cells[1, 2] = "Author";
        xlWorkSheet.Cells[1, 3] = "Rating";

        string curFile = @"g:\Biblioteca.xls";

        if (!File.Exists(curFile))
        {
            xlWorkBook.SaveAs("g:\\Biblioteca.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
            xlWorkSheet.Cells[++k, 1] = getName;
            xlWorkSheet.Cells[k, 2] = getAuthor;    
            xlWorkSheet.Cells[k, 3] = getRating;
            MessageBox.Show("Excel created succesfuly");
        }
        else
        {

            Excel.Application excelApp = (Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
            Excel.Workbook excelWorkbook = excelApp.Workbooks.Open(curFile,
                    0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "",
                    true, false, 0, true, false, false);
            xlWorkSheet.Cells[++k, 1] = getName;
            xlWorkSheet.Cells[k, 2] = getAuthor;
            xlWorkSheet.Cells[k, 3] = getRating;
        }
        xlWorkBook.Close(true, misValue, misValue);
        xlApp.Quit();


    }

}

1 个答案:

答案 0 :(得分:0)

您没有打开任何现有文件!

有关打开现有电子表格的示例,请参阅@ gmiley的第二个参考。您可能需要学习Range以了解如何放置新数据。