codice:
private void EsportaInTemplateExcelVL(string NomeFile,dt as datatable)
{
string fileNameTemp = NomeFile;//System.IO.Path.GetTempPath() + Guid.NewGuid().ToString() + ".xlsx";
string FileXls = Application.StartupPath + @"\Support\PrintFormat\VL_LAB_updated.xls";
if (!File.Exists(FileXls))
{
MessageBox("File template VL_LAB_updated.xls not found");
return;
}
System.IO.File.Copy(FileXls, fileNameTemp);
Excel.Application excelApp = new Excel.Application();
Excel.Workbook wb = excelApp.Application.Workbooks.Open(fileNameTemp, 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, Type.Missing);
Excel.Sheets excelSheets = excelApp.Worksheets;// var ws = excelApp.Worksheets;
Excel.Worksheet excelWorksheet = (Excel.Worksheet)excelSheets.get_Item("DATA");
// Excel.Worksheet worksheet = ws.get_Item("Sheet1");//(Microsoft.Office.Interop.Excel.Worksheet)
// Excel.Range range = worksheet.UsedRange;
// object[,] values = (object[,])range.Value2;
string[] col = { "A", "B", "C", "D", "E", "F", "G", "H", "I","J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X","Y", "Z" };
//scrittura intestazioni colonna
for (int C = 0; C < dt.Columns.Count ; C++)
{
string Cella = col[C].ToString() + (0 + 1).ToString();//i parte da zero
Excel.Range excelCell = (Excel.Range)excelWorksheet.get_Range(Cella, Cella);
excelCell.Value = dt.Columns[C].ColumnName;
}
for (int i = 0; i < dt.Rows.Count ; i++)//parte da 1 per mantenere titolo
{
//DataRow Dr = dt.Rows[i];
for (int C = 0; C < dt.Columns.Count ; C++)//dt.Rows.Count-1
{
string Cella = col[C].ToString() + (i + 2).ToString();//i parte da zero
Excel.Range excelCell = (Excel.Range)excelWorksheet.get_Range(Cella, Cella);
excelCell.Value = "'" + dt.Rows[i][C].ToString();// "Hi There2";
}
}
wb.Close(true);
//excelApp.Save();//fileNameTemp
excelApp.Quit();
MessageBox("Done");
}