코드를 Excel로 내보내는 방법이 궁금합니다. 내 toolstripmenu 클릭이 코드가 있습니다.Datagridview 내보내기가 작동하지 않습니다.
private void excelFileToolStripMenuItem_Click(object sender, EventArgs e)
{
string[] arrays = new string[this.dgvResult.Columns.Count];
int icol = 0;
foreach (DataGridViewColumn gridColum in this.dgvResult.Columns)
{
//for (irow = 0; irow <= this.dgvResult.Columns.Count - 1; irow++)
//{
arrays[icol] = this.dgvResult.Columns[icol].Name;
icol++;
// }
}
SystemUtil.ExportToExel_DG(dgvResult, arrays, "", "");
}
내가 엑셀 내보내기 엑셀
public void ExportToExel_DG(DataGridView dg, string[] arrays,string sTitle,string sRundate)
{
try
{
Excel.Application oXL;
Excel.Workbook oWB;
Excel.Worksheet oSheet;
//Excel.Range oRange;
oXL = new Excel.Application();
// Set some properties
oXL.Visible = true;
oXL.DisplayAlerts = false;
// Get a new workbook.
oWB = oXL.Workbooks.Add(Missing.Value);
// Get the active sheet
oSheet = (Excel.Worksheet)oWB.ActiveSheet;
oSheet.Name = "Attachment";
//Title
//oSheet.Cells[1, 2] = "Corporate Name:" + sTitle;
//oSheet.Cells[2, 2] = "Utilization Reports";
//oSheet.Cells[3, 2] = "Run Date: " + sRundate;
int rowCount = 1;
int RecNo = 1;
foreach (DataGridViewRow dgr in dg.Rows)
{
int iCell = 2;
rowCount += 1;
for (int i = 1; i <= dg.ColumnCount; i++)
{
if (rowCount == 1)
{
oSheet.Cells[1, 1] = "Record No.";
oSheet.Cells[1, iCell] = arrays[i - 1];// dt.Columns[i - 1].ColumnName;
}
oSheet.Cells[rowCount, 1] = RecNo;
oSheet.Cells[rowCount, iCell] = dgr.Cells[i - 1].Value.ToString();
iCell++;
}
RecNo++;
}
oSheet.Cells[rowCount + 1, 2] = "TOTAL";
oSheet.Columns.AutoFit();
oSheet = null;
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
}
catch
{
}
}
나는 도구 스트립 메뉴를 클릭 할 때마다에 내 DataGridView에 항목을 내보내려면이 클래스에서이 코드를 가지고, 빈 엑셀 통합 문서는 팝업 내 데이터 표보기에서 내보내려는 항목이 없습니다. 나는 C# 응용 프로그램을 만들 때 새로운 것이다.
try/catch를 제거하십시오. 문제를 해결하지 않고 문제를 숨기고 있습니다. 또한 모든 'GC'물건을 제거해야합니다. 이 기사를 처음 접한다면, 그 코드가 무엇을하는지 전혀 알 수 없습니다. –
@JohnSaunders try/catch를 제거했습니다. 오류는 없지만 팝업되는 통합 문서는 여전히 비어 있습니다. –
좋습니다. 이제 오류가 없음을 알았습니다. 이전에는 오류가 있었지만 알 수 없었을 것입니다. –