动态读取和写入Excel工作表

时间:2014-04-18 17:09:48

标签: c# excel

我尝试创建一个包含多个工作表的新Excel文件(#lip = NameList中的#个项目)。然后每个工作表应使用NameList中的相应条目命名。完成此操作后,我需要一种方法来调用每张表。

我遇到的问题是:工作表不喜欢设置为List而不接受(Excel.Worksheet)工作簿中的变量.Sheets [variable]

我可以完美地写一张纸,但是任何创建纸张的尝试都失败了。

    public CreateExcelDoc excell_app { get; set; }
    public Excel.Workbook workbook { get; set; }
    public List<string> NameList = new List<string>();
    public List<Excel.Worksheet> worksheets { get; set; } // tried: = new List<Excel.Worksheet>();


    public void setupFile(int i) // this method errors on each of the 2 lines
            {
                worksheets[i] = (Excel.Worksheet)workbook.Worksheets.Add();
                worksheets[i].Name = NameList[i];
            } // this method is in a separate public class from CreateExcelDoc


        public class CreateExcelDoc
        {
            private Excel.Application app = null;
            Excel.Workbook workbook = null;
            Excel.Worksheet worksheet = null;
            private Excel.Range workSheet_range = null;
            public CreateExcelDoc()
            {
                try
                {
                    app = new Excel.Application();
                    app.Visible = true;
                    workbook = app.Workbooks.Add(1);
                    //worksheets[0] = (Excel.Worksheet)workbook.Sheets[1];
                    //worksheet.Name = "t";
                }
                catch (Exception e)
                {
                    MessageBox.Show("Exception Occured while exporting to Excel doc. Error: " + e.ToString());
                }
                finally
                {
                }
            }
    _Other Methods for writing to cells omitted_
    }

0 个答案:

没有答案
相关问题