sto cercando di aggiungere a livello di codice fogli a un nuovo documento Excel.
il mio output atteso è fogli chiamati "test1-20" ma invece ottengo "Sheet1-19, test20".
perché non funziona?
Workbook workbook;
Application objExcel;
objExcel = new Application();
objExcel.Visible = false;
objExcel.DisplayAlerts = false;
for (var i = 0; i < worksheets.Count; i++)
{
workbook= objExcel.Workbooks.Add(Missing.Value);
var worksheet = (Worksheet)workbook.Worksheets.get_Item(i + 1);
worksheet.Name = string.Format("test{0}", i + 1);
}
risposte:
4 per risposta № 1Prova questo:
using System;
using System.Runtime.InteropServices;
using Excel = Microsoft.Office.Interop.Excel;
void MyMethod()
{
try
{
var _excel = new Excel();
var wb = _excel.Workbooks.Add();
var collection = new Microsoft.Office.Interop.Excel.Worksheet[20];
for (var i = 19; i >= 0; i--)
{
collection[i] = wb.Worksheets.Add();
collection[i].Name = String.Format("test{0}", i + 1);
}
for (var i = 0; i < 3; i++)
{
wb.Worksheets[21].Delete();
}
//collection is an array of worksheet objects,
//the worksheet objects in your workbook.
//You can access each individual worksheet and
//work with it in the same way you access any object in an array
var thisWorksheet = collection[9];
var thisRange = thisWorksheet.Range["A1"];
thisRange.Value = "Hello World";
wb.SaveAs(@"c:testwhatever.xlsx");
wb.Close();
}
finally
{
Marshal.ReleaseComObject(_excel);
}
}
La tua proprietà visibile è impostata su false per impostazione predefinita,quindi non è necessario farlo esplicitamente, non viene visualizzato alcun avviso nel codice sopra, quindi neanche questo è necessario. Ho testato il codice sopra e posso confermare che funziona.
0 per risposta № 2
Ecco il mio codice che fa questo:
" first worksheet
If oExcel.Application.Sheets.Count() < 1 Then
oSheet = CType(oBook.Worksheets.Add(), Excel.Worksheet)
Else
oSheet = oExcel.Worksheets(1)
End If
oSheet.Name = "one"
oSheet.Range("B1").Value = "First One"
" second
If oExcel.Application.Sheets.Count() < 2 Then
oSheet = CType(oBook.Worksheets.Add(), Excel.Worksheet)
Else
oSheet = oExcel.Worksheets(2)
End If
oSheet.Name = "two"
oSheet.Range("B1").Value = "Second one"
" third
If oExcel.Application.Sheets.Count() < 3 Then
oSheet = CType(oBook.Worksheets.Add(), Excel.Worksheet)
Else
oSheet = oExcel.Worksheets(3)
End If
oSheet.Name = "three"
oSheet.Range("B1").Value = "Thrid"
" next
If oExcel.Application.Sheets.Count() < 4 Then
oSheet = CType(oBook.Worksheets.Add(), Excel.Worksheet)
Else
oSheet = oExcel.Worksheets(4)
End If
oSheet.Name = "four"
oSheet.Range("B1").Value = "Four"