【问题标题】:Opening an Excel File through C# and writing data通过 C# 打开 Excel 文件并写入数据
【发布时间】:2014-09-02 05:53:35
【问题描述】:

我有一个应用程序尝试打开存储在特定位置的 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";
        }
    }
}

问题一: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:它总是最终进入异常循环。

请帮忙。

这是表单的样子:

【问题讨论】:

  • 善意的建议:使用像 EPPLUS 这样的库来读取/写入 excel 文件。在开发过程中更快、更有弹性、更少头痛
  • @ChristianSauer:感谢您的建议。要保存的数据不是那么大。所以我避免使用额外的库。这段代码工作得很好,没有任何延迟。如果您能提供帮助,我遇到的唯一问题如下所列。
  • 暂时删除 try/catch 块,看看你在哪一行得到了异常。我相信这不是行oWB = oXL.Workbooks.Open(...
  • @VDonhal :我确实尝试过,发现异常发生在“oWB.SaveAs”
  • @VDohnal:异常详细信息:Microsoft Excel 无法访问文件“C:\Users\diwesh\Documents\Excel\4BCD5420”。有几个可能的原因: • 文件名或路径不存在。

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


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-30
    • 1970-01-01
    • 1970-01-01
    • 2017-08-26
    • 1970-01-01
    • 1970-01-01
    • 2017-11-01
    相关资源
    最近更新 更多