4
我處於簡單方法的中間,將我的DataGridView保存到Excel文檔(僅1張)中,並添加了VBA代碼和一個運行VBA代碼的按鈕。以編程方式從C#創建Excel VBA代碼和按鈕#
public void SaveFile(string filePath)
{
Microsoft.Office.Interop.Excel.ApplicationClass ExcelApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
ExcelApp.Application.Workbooks.Add(Type.Missing);
//Change Workbook-properties.
ExcelApp.Columns.ColumnWidth = 20;
// Storing header part in Excel.
for (int i = 1; i < gridData.Columns.Count + 1; i++)
{
ExcelApp.Cells[1, i] = gridData.Columns[i - 1].HeaderText;
}
//Storing Each row and column value to excel sheet
for (int row = 0; row < gridData.Rows.Count; row++)
{
gridData.Rows[row].Cells[0].Value = "Makro";
for (int column = 0; column < gridData.Columns.Count; column++)
{
ExcelApp.Cells[row + 2, column + 1] = gridData.Rows[row].Cells[column].Value.ToString();
}
}
ExcelApp.ActiveWorkbook.SaveCopyAs(filePath);
ExcelApp.ActiveWorkbook.Saved = true;
ExcelApp.Quit();
}
我只實現了DataGridView導出。
編輯:感謝喬爾,我可以用適當的話再次搜索解決方案。我認爲那this may be helpful。你會糾正我還是給我一兩個關於我應該找的東西。
你是說,你要一個宏添加到新的工作簿編程方式(從代碼中此信息)? –
是的。一個新的宏和一個將運行它的按鈕。 – 1GurU9