通过C#打开Excel文件并写入数据

时间:2014-09-02 05:53:36

标签: excel c#-4.0 visual-studio-2012 export-to-excel

enter image description here

我有一个应用程序试图打开存储在特定位置的Excel文件并向其写入一些数据内容。

这是我的代码:

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {

                //String inputFile = @"D:\Excel\Input.xlsx";

                Excel.Application oXL = new Excel.Application();


#if DEBUG
                oXL.Visible = true;
                oXL.DisplayAlerts = true;
#else
                oXL.Visible = false; 
                oXL.DisplayAlerts = false;
#endif


                //Open a New Excel File

              // Excel.Workbook oWB = oXL.Workbooks.Add(Type.Missing);

             Excel.Workbook   oWB = oXL.Workbooks.Open("C:\\Users/diwesh/Downloads/WriteExcel/WriteExcel/WindowsFormsApplication1/bin/Debug/Input.xlsx");

               // Excel.Workbook oWB = oXL.Workbooks.Open(@".\Input.xlsx");


                Excel._Worksheet oSheet = oWB.ActiveSheet;




                oSheet.Cells[1, 1] = "Name";  
                oSheet.Cells[1, 2] = "Percentage(%)"; // Here 1 is the rowIndex and 2 is the columnIndex.
                oSheet.Cells[1, 3] = txt_Name.Text;


                //Format the Header row to make it Bold and blue
                oSheet.get_Range("A1", "B1").Interior.Color = Color.SkyBlue;
                oSheet.get_Range("A1", "B1").Font.Bold = true;
                //Set the column widthe of Column A and Column B to 20
                oSheet.get_Range("A1", "B12").ColumnWidth = 20;

                oSheet.get_Range("A1", "B3").Font.Bold = true;

               // String ReportFile = @"D:\Excel\Output.xls";
                String ReportFile = @".\Excel\Output.xls";
                oWB.SaveAs(ReportFile, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookDefault,
                                        Type.Missing, Type.Missing,
                                        false,
                                        false,
                                        Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange,
                                        Type.Missing,
                                        Type.Missing,
                                        Type.Missing,
                                        Type.Missing,
                                        Type.Missing);


                oXL.Quit();

                Marshal.ReleaseComObject(oSheet);
                Marshal.ReleaseComObject(oWB);
                Marshal.ReleaseComObject(oXL);

                oSheet = null;
                oWB = null;
                oXL = null;
                GC.GetTotalMemory(false);
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.GetTotalMemory(true);
            }
            catch (Exception ex)
            {
                String errorMessage = "Error reading the Excel file : " + ex.Message;
                MessageBox.Show(errorMessage, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

                //MessageBox.Show("Thank you the excel data has been saved");
            }

        }


        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void button2_Click(object sender, EventArgs e)
        {
            txt_Name.Text = "Diwesh";
        }
    }
}

麻烦1:Excel.Workbook oWB = oXL.Workbooks.Open(@".\Input.xlsx");

这找不到" Input.xlsx"并打开应用程序,除非我给它一个完整的路径,如:

Excel.Workbook oWB = oXL.Workbooks.Open("C:\\Users/diwesh/Downloads/WriteExcel/WriteExcel/WindowsFormsApplication1/bin/Debug/Input.xlsx");

麻烦2:它总是最终进入异常循环。

请帮忙。

这就是表单的样子:

enter image description here

1 个答案:

答案 0 :(得分:0)

您尝试创建这样的路径,而不是使用相对路径:

String example01 = System.Reflection.Assembly.GetExecutingAssembly().Location;
String resultPath = System.IO.Path.Combine(
            System.IO.Path.GetDirectoryName(example01),
            "test.xlsx"
            );

这假设您的Excel文件与您的应用程序位于同一目录中。