C#拆分工作表
时间: 2023-07-12 07:16:38 浏览: 88
工作表拆分工具
4星 · 用户满意度95%
你可以使用C#中的Excel Interop来拆分工作表。下面是一个简单的示例代码:
```csharp
using Excel = Microsoft.Office.Interop.Excel;
public void SplitWorksheet(string filePath, string sheetName, int numberOfRowsPerSheet)
{
Excel.Application excel = new Excel.Application();
Excel.Workbook workbook = excel.Workbooks.Open(filePath);
Excel.Worksheet worksheet = workbook.Sheets[sheetName];
Excel.Range usedRange = worksheet.UsedRange;
int rowCount = usedRange.Rows.Count;
int colCount = usedRange.Columns.Count;
// Create new workbooks and sheets
int sheetCount = (int)Math.Ceiling((double)rowCount / numberOfRowsPerSheet);
for (int i = 1; i <= sheetCount; i++)
{
Excel.Workbook newWorkbook = excel.Workbooks.Add();
Excel.Worksheet newWorksheet = newWorkbook.Sheets[1];
// Copy headers to new worksheet
Excel.Range headerRange = worksheet.Range[worksheet.Cells[1, 1], worksheet.Cells[1, colCount]];
headerRange.Copy(newWorksheet.Range[newWorksheet.Cells[1, 1], newWorksheet.Cells[1, colCount]]);
// Copy rows to new worksheet
int startRow = (i - 1) * numberOfRowsPerSheet + 1;
int endRow = Math.Min(i * numberOfRowsPerSheet, rowCount);
Excel.Range dataRange = worksheet.Range[worksheet.Cells[startRow, 1], worksheet.Cells[endRow, colCount]];
dataRange.Copy(newWorksheet.Range[newWorksheet.Cells[2, 1], newWorksheet.Cells[endRow - startRow + 2, colCount]]);
// Save new workbook
string newFilePath = Path.GetDirectoryName(filePath) + "\\" + Path.GetFileNameWithoutExtension(filePath) + "_" + i + ".xlsx";
newWorkbook.SaveAs(newFilePath);
newWorkbook.Close();
}
// Close original workbook
workbook.Close();
excel.Quit();
}
```
此代码将打开指定的Excel文件,并在指定的工作表上拆分行数。它将创建多个新的工作簿,并将工作表中的行分配给新的工作表。每个新的工作簿都将保存为单独的文件。
阅读全文