我有一个包含25个左右工作表的excel我只想保存每个工作表,因为它是自己的新工作簿。当我运行代码时,它会复制整个工作簿而不是单个工作表。任何帮助都会很棒。
string FileDropLocation = @"C:\ExcelFiles";
string file_FullFileName = @"C:\ts\Conversion\v2.xlsx";
Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook workBook = app.Workbooks.Open(file_FullFileName, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
for (int i = 0; i < workBook.Worksheets.Count; i++)
{
Microsoft.Office.Interop.Excel.Worksheet workSheet = (Microsoft.Office.Interop.Excel.Worksheet)workBook.Sheets[i+1];
workSheet.SaveAs(FileDropLocation + "\\" + workSheet.Name);
}
workBook.Close();
答案 0 :(得分:1)
我知道这很有效。
Microsoft.Office.Interop.Excel.Application xl = null;
Microsoft.Office.Interop.Excel._Workbook wb = null;
xl = new Microsoft.Office.Interop.Excel.Application();
xl.SheetsInNewWorkbook = 1;
xl.Visible = true;
wb = (Microsoft.Office.Interop.Excel._Workbook)(xl.Workbooks.Add(Type.Missing));
wb.SaveAs(FileDropLocation + "\\" + workBook.Sheets[i + 1].Name, Microsoft.Office.Interop.Excel.XlFileFormat.xlExcel8, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
wb.Close(true, Type.Missing, Type.Missing);
xl.Quit();
Microsoft.Office.Interop.Excel.Workbook destWorkbook = null;
Microsoft.Office.Interop.Excel.Worksheet workSheet = null;
Microsoft.Office.Interop.Excel.Worksheet newWorksheet = null;
destWorkbook = app.Workbooks.Open(FileDropLocation + "\\" + workBook.Sheets[i + 1].Name + ".xls", false, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
workSheet = (Microsoft.Office.Interop.Excel.Worksheet)workBook.Sheets[i + 1];
newWorksheet = (Microsoft.Office.Interop.Excel.Worksheet)destWorkbook.Worksheets.Add(Type.Missing, Type.Missing, Type.Missing, Type.Missing);
app.DisplayAlerts = false;
workSheet.Copy(Type.Missing,newWorksheet);
destWorkbook.Save();
答案 1 :(得分:0)
...您需要在循环中创建一个新工作簿并将工作表移动到该工作簿。 我在VB中编程,所以我猜,但你的foor循环中的代码应该是这样的:
Microsoft.Office.Interop.Excel.Workbook workBook2 = app.Workbooks.Add(Missing.Value)
Microsoft.Office.Interop.Excel.Worksheet workSheet = (Microsoft.Office.Interop.Excel.Worksheet)workBook.Sheets[i+1];
workSheet.Copy(workBook2.Sheets(1))
然后您可以添加代码来删除其他工作表等。
希望有所帮助。