如何在Excel文件C#中创建新的工作表? [英] How to create a new worksheet in Excel file c#?

查看:245
本文介绍了如何在Excel文件C#中创建新的工作表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要创建一个非常大的Excel文件,但是一个工作表中的excel文件最多可以包含65k行.因此,我想将我所有的信息动态地分为几个工作表. 这是我的大概代码

I need to create a very big Excel file, but excel file in one worksheet can contain up to 65k rows. So, i want to divide all my info into several worksheets dynamical. This is my approximate code

 //------------------Create Excel App--------------------
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;

xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(numberOfLetters);

     foreach (string letter in letters)
     {
      xlWorkSheet.Cells[rowIndex, 1] = letter; 
      rowIndex++;
     }

xlWorkBook.SaveAs(pathXL, Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();

我如何在foreach循环中添加新工作表并使用某种条件为工作表命名(用户可以在列表页面底部的Excel中看到该表)?

How I can add new worksheet inside of my foreach loop and using some condition give a name to worksheet (which user can see in Excel at the bottom of the page in list)?

类似的东西

    foreach (string letter in letters)
    {
      if (letter == SOME)
      {
        AddNewWorksheet and give name SOME
      }
        xlWorkSheet.Cells[rowIndex, 1] = letter; 
        rowIndex++;
    }

以及如何在最后保存所有工作表?

And how to save all worksheets at the end?

推荐答案

要将新工作表添加到工作簿,请使用以下代码:

To add a new worksheet to the workbook use this code:

var xlSheets = xlWorkBook.Sheets as Excel.Sheets;
var xlNewSheet = (Excel.Worksheet)xlSheets.Add(xlSheets[1], Type.Missing, Type.Missing, Type.Missing);
xlNewSheet.Name = "newsheet";

// Uncomment a line below if you want the inserted sheet to be the last one
//xlWorkBook.Sheets.Move(After: xlWorkBook.Sheets.Count);

要保存工作簿调用Save()方法:

To save the workbook call Save() method:

xlWorkBook.Save();

这篇关于如何在Excel文件C#中创建新的工作表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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