C#Excel写入多个单元格

时间:2016-03-30 12:54:24

标签: c# excel office-interop

您好我尝试使用c#excel的东西变得更好。现在我尝试从现有的excelsheet中选择一些值。例如:从B4到C16。所以我可以用其他东西替换这些值,但我不能让它起作用。

这是我的小方法:

public void writeExcelFile()
        {

            string path = @"C:\Users\AAN\Documents\Visual Studio 2015\Projects\WorkWithExcel\WorkWithExcel\bin\Debug\PROJEKTSTATUS_GESAMT_neues_Layout.xlsm";
            oXL = new Excel.Application();
            oXL.Visible = true;
            oXL.DisplayAlerts = false;
            mWorkBook = oXL.Workbooks.Open(path, 0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
            //Get all the sheets in the workbook
            mWorkSheets = mWorkBook.Worksheets;
            //Get the allready exists sheet
            mWSheet1 = (Excel.Worksheet)mWorkSheets.get_Item(1);
            //Excel.Range range = mWSheet1.UsedRange;
            //int colCount = range.Columns.Count;
            //int rowCount = range.Rows.Count;
            int countRows = mWSheet1.UsedRange.Rows.Count;
            int countColumns = mWSheet1.UsedRange.Columns.Count;
            object[,] data = mWSheet1.Range[mWSheet1.Cells[1, 1], mWSheet1.Cells[countRows, countColumns]].Cells.Value2;

            for (int index = 1; index < 15; index++)
            {
                mWSheet1.Cells[countRows + index, 1] = countRows + index;
                mWSheet1.Cells[countRows + index, 2] = "test" + index;
            }

            //Excel.Worksheet sheet = workbook.ActiveSheet;
            //Excel.Range rng = (Excel.Range)sheet.get_Range(sheet.Cells[1, 1], sheet.Cells[3, 3]);

            mWorkBook.SaveAs(path, Excel.XlFileFormat.xlOpenXMLWorkbookMacroEnabled,Missing.Value, Missing.Value, Missing.Value, Missing.Value, Excel.XlSaveAsAccessMode.xlExclusive,Missing.Value, Missing.Value, Missing.Value,Missing.Value, Missing.Value);
            mWorkBook.Close(Missing.Value, Missing.Value, Missing.Value);
            mWSheet1 = null;
            mWorkBook = null;
            oXL.Quit();
            GC.WaitForPendingFinalizers();
            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();
        }

我用get_range尝试了它,但我得到一个例外,这是不可行的。 它与Microsoft.Office.Interop libary 14有关。然后我用对象[,]尝试了它,但我唯一需要工作的是,毕竟使用单元格插入测试但不选择任何东西。所以任何帮助都会很棒。

感谢您的时间,对不起我的英语。

编辑:至少读取过程现在正常工作,我循环到选定的范围。 这是工作代码:

        public void writeExcelFile()
        {

            String inputFile = @"C:\Users\AAN\Documents\Visual Studio 2015\Projects\WorkWithExcel\WorkWithExcel\bin\Debug\PROJEKTSTATUS_GESAMT_neues_Layout.xlsm";

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


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


            //Open the Excel File
            Excel.Workbook oWB = oXL.Workbooks.Open(inputFile);

            String SheetName = "Gesamt";
            Excel._Worksheet oSheet = oWB.Sheets[SheetName];

            String start_range = "B4";
            String end_range = "R81";

            Object[,] values = oSheet.get_Range(start_range, end_range).Value2;

            int t = values.GetLength(0);
            for (int i = 1; i <= values.GetLength(0); i++)
            {
                String val = values[i, 1].ToString();
            }

            oXL.Quit();

        }

1 个答案:

答案 0 :(得分:0)

经过多次尝试,我终于得到了一个可行的解决方案,我可以选择我想要的任何细胞。 Maby有更好的方法,但对我来说它按预期工作。

代码:

        public void writeExcelFile()
        {

            try
            {

                String inputFile = @"C:\Users\AAN\Documents\Visual Studio 2015\Projects\WorkWithExcel\WorkWithExcel\bin\Debug\PROJEKTSTATUS_GESAMT_neues_Layout.xlsm";

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


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


                //Open a Excel File
                Excel.Workbook oWB = oXL.Workbooks.Add(inputFile);
                Excel._Worksheet oSheet = oWB.ActiveSheet;

                List<String> Name = new List<String>();
                List<Double> Percentage = new List<Double>();

                Name.Add("Anil");
                Name.Add("Vikas");
                Name.Add("Ashwini");
                Name.Add("Tobias");
                Name.Add("Stuti");
                Name.Add("Raghavendra");
                Name.Add("Chithra");
                Name.Add("Glen");
                Name.Add("Darren");
                Name.Add("Michael");


                Percentage.Add(78.5);
                Percentage.Add(65.3);
                Percentage.Add(56);
                Percentage.Add(56);
                Percentage.Add(97);
                Percentage.Add(89);
                Percentage.Add(85);
                Percentage.Add(76);
                Percentage.Add(78);
                Percentage.Add(89);

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


                //Enter the Header data in Column A
                int i = 0;
                for (i = 0; i < Name.Count; i++)
                {
                    oSheet.Cells[i + 2, 1] = Name[i];
                }

                //Enter the Percentage data in Column B
                for (i = 0; i < Percentage.Count; i++)
                {
                    oSheet.Cells[i + 2, 2] = Percentage[i];
                }

                oSheet.Cells[Name.Count + 3, 1] = "AVERAGE";
                //Obtain the Average of the Percentage Data
                string currentFormula = "=AVERAGE(B2:" + "B" + Convert.ToString(Percentage.Count + 1) + ")";

                oSheet.Cells[Percentage.Count + 3, 2].Formula = currentFormula;

                //Format the Header row to make it Bold and blue
                oSheet.get_Range("A1", "B1").Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.AliceBlue);
                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;

                //String ReportFile = @"D:\Excel\Output.xls";
                oWB.SaveAs(inputFile, Excel.XlFileFormat.xlOpenXMLWorkbookMacroEnabled,
                                        Type.Missing, Type.Missing,
                                        false,
                                        false,
                                        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);
            }

        }

这不是我自己的代码来自博客:the blog where i got it刚编辑,所以它对我有用。