반응형
C# 윈폼에서 DataGridView Data를 Excel 파일로 저장하는 소스를 알려 드리겠습니다. 순수하게 제가 만든건 아니고 여러 사이트에서 소스를 참조해서 제 상황에 맞게끔 응용을 했습니다.
제가 MS 오피스 2007 에 Visual Studio 2008 을 쓰기 때문에 이를 기준으로 소개를 하겠습니다.
먼저 솔루션 탐색기에서 참조추가를 합니다.
이후 아래 소스를 적용하시면 됩니다.
제가 MS 오피스 2007 에 Visual Studio 2008 을 쓰기 때문에 이를 기준으로 소개를 하겠습니다.
먼저 솔루션 탐색기에서 참조추가를 합니다.
솔루션탐색기->참조추가->COM->Microsoft Excel 12.0 Object Libary 선택
이후 아래 소스를 적용하시면 됩니다.
using System.Reflection;
using Excel = Microsoft.Office.Interop.Excel;
private void ExportExcel(bool captions)
{
this.saveFileDialog.FileName = "TempName";
this.saveFileDialog1.DefaultExt = "xls";
this.saveFileDialog1.Filter = "Excel files (*.xls)|*.xls";
this.saveFileDialog1.InitialDirectory = "c:\\";
DialogResult result = saveFileDialog.ShowDialog();
if (result == DialogResult.OK)
{
int num = 0;
object missingType = Type.Missing;
Excel.Application objApp;
Excel._Workbook objBook;
Excel.Workbooks objBooks;
Excel.Sheets objSheets;
Excel._Worksheet objSheet;
Excel.Range range;
string[] headers = new string[dataGridView.ColumnCount];
string[] columns = new string[dataGridView.ColumnCount];
for (int c = 0; c < dataGridView.ColumnCount; c++)
{
headers[c]=dataGridView.Rows[0].Cells[c].OwningColumn.HeaderText.ToString();
num = c + 65;
columns[c] = Convert.ToString((char)num);
}
try
{
objApp = new Excel.Application();
objBooks = objApp.Workbooks;
objBook = objBooks.Add(Missing.Value);
objSheets = objBook.Worksheets;
objSheet = (Excel._Worksheet)objSheets.get_Item(1);
if (captions)
{
for (int c = 0; c < dataGridView.ColumnCount; c++)
{
range = objSheet.get_Range(columns[c] + "1", Missing.Value);
range.set_Value(Missing.Value, headers[c]);
}
}
for (int i = 0; i < dataGridView.RowCount - 1; i++)
{
for (int j = 0; j < dataGridView.ColumnCount; j++)
{
range = objSheet.get_Range(columns[j] + Convert.ToString(i + 2),
Missing.Value);
range.set_Value(Missing.Value,
dataGridView.Rows[i].Cells[j].Value.ToString());
}
}
objApp.Visible = false;
objApp.UserControl = false;
objBook.SaveAs(@saveFileDialog.FileName,
Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal,
missingType, missingType, missingType, missingType,
Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange,
missingType, missingType, missingType, missingType, missingType);
objBook.Close(false, missingType, missingType);
Cursor.Current = Cursors.Default;
MessageBox.Show("Save Success!!!");
}
catch (Exception theException)
{
String errorMessage;
errorMessage = "Error: ";
errorMessage = String.Concat(errorMessage, theException.Message);
errorMessage = String.Concat(errorMessage, " Line: ");
errorMessage = String.Concat(errorMessage, theException.Source);
MessageBox.Show(errorMessage, "Error");
}
}
}
using Excel = Microsoft.Office.Interop.Excel;
private void ExportExcel(bool captions)
{
this.saveFileDialog.FileName = "TempName";
this.saveFileDialog1.DefaultExt = "xls";
this.saveFileDialog1.Filter = "Excel files (*.xls)|*.xls";
this.saveFileDialog1.InitialDirectory = "c:\\";
DialogResult result = saveFileDialog.ShowDialog();
if (result == DialogResult.OK)
{
int num = 0;
object missingType = Type.Missing;
Excel.Application objApp;
Excel._Workbook objBook;
Excel.Workbooks objBooks;
Excel.Sheets objSheets;
Excel._Worksheet objSheet;
Excel.Range range;
string[] headers = new string[dataGridView.ColumnCount];
string[] columns = new string[dataGridView.ColumnCount];
for (int c = 0; c < dataGridView.ColumnCount; c++)
{
headers[c]=dataGridView.Rows[0].Cells[c].OwningColumn.HeaderText.ToString();
num = c + 65;
columns[c] = Convert.ToString((char)num);
}
try
{
objApp = new Excel.Application();
objBooks = objApp.Workbooks;
objBook = objBooks.Add(Missing.Value);
objSheets = objBook.Worksheets;
objSheet = (Excel._Worksheet)objSheets.get_Item(1);
if (captions)
{
for (int c = 0; c < dataGridView.ColumnCount; c++)
{
range = objSheet.get_Range(columns[c] + "1", Missing.Value);
range.set_Value(Missing.Value, headers[c]);
}
}
for (int i = 0; i < dataGridView.RowCount - 1; i++)
{
for (int j = 0; j < dataGridView.ColumnCount; j++)
{
range = objSheet.get_Range(columns[j] + Convert.ToString(i + 2),
Missing.Value);
range.set_Value(Missing.Value,
dataGridView.Rows[i].Cells[j].Value.ToString());
}
}
objApp.Visible = false;
objApp.UserControl = false;
objBook.SaveAs(@saveFileDialog.FileName,
Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal,
missingType, missingType, missingType, missingType,
Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange,
missingType, missingType, missingType, missingType, missingType);
objBook.Close(false, missingType, missingType);
Cursor.Current = Cursors.Default;
MessageBox.Show("Save Success!!!");
}
catch (Exception theException)
{
String errorMessage;
errorMessage = "Error: ";
errorMessage = String.Concat(errorMessage, theException.Message);
errorMessage = String.Concat(errorMessage, " Line: ");
errorMessage = String.Concat(errorMessage, theException.Source);
MessageBox.Show(errorMessage, "Error");
}
}
}
'프로그래밍' 카테고리의 다른 글
[C#] Ping Test Code (0) | 2009.12.15 |
---|---|
C# Content-Transfer-Encoding 설정 코드 (0) | 2009.07.04 |
모바일 게임 개발 (17) | 2009.04.14 |
Effective C# 정리 (0) | 2009.04.08 |