C#Excel写入多个单元格 [英] C# Excel Write to multiple cells

查看:143
本文介绍了C#Excel写入多个单元格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用C#Excel东西变得更好.现在,我尝试从现有的excelsheet中选择一些值.例如:从B4到C16.所以我可以用其他东西代替这些值,但我无法使其正常工作.

Hi i try to get better with the c# excel stuff. Right now i try to select some values from an existing excelsheet. For Example: From B4 to C16. So i can replace the values with something else but i dont get it to work.

这是我的小方法:

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库14有关.然后,我使用object [,]进行了尝试,但我唯一要做的事情是,毕竟所有单元格都用于插入测试但没有选择任何内容.因此,任何帮助都会很棒.

I tried it with get_range but i get an exception that this is not aviable. It has something to do with the Microsoft.Office.Interop libary 14. Then i tried it with object[,] but the only thing i got to work is that after all used cells to insert test but not to select anything. So any help would be great.

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

Thanks for your Time and sorry for my english.

至少读取过程现在可以正常工作,并且我循环通过选定范围. 这是工作代码:

At least the read process works now and i loop trough a selected range. Here is the working code:

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

        }

推荐答案

经过多次尝试,我终于找到了一个可行的解决方案,可以在其中选择所需的任何单元格. Maby有更好的方法,但是对我来说,它可以按预期工作.

After many tries i finnaly got a working solution where i can select any cells i want. Maby there are better ways but for me it works as expected.

代码:

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

        }

这不是我自己的博客文章代码:

This is not my own code its from a blog: the blog where i got it just edited so it works for me.

这篇关于C#Excel写入多个单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆