C\#에서 DataGridView 에서 Excel 을 내 보 내 는 두 가지 방법
7226 단어 C#DataGridView도 출Excel
#region
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "Execl files (*.xls)|*.xls";
saveFileDialog.FilterIndex = 0;
saveFileDialog.RestoreDirectory = true;
saveFileDialog.CreatePrompt = true;
saveFileDialog.Title = "Export Excel File";
saveFileDialog.ShowDialog();
if (saveFileDialog.FileName == "")
return;
Stream myStream;
myStream = saveFileDialog.OpenFile();
StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0));
string str = "";
try
{
for (int i = 0; i < dataGridView1.ColumnCount; i++)
{
if (i > 0)
{
str += "\t";
}
str += dataGridView1.Columns[i].HeaderText;
}
sw.WriteLine(str);
for (int j = 0; j < dataGridView1.Rows.Count; j++)
{
string tempStr = "";
for (int k = 0; k < dataGridView1.Columns.Count; k++)
{
if (k > 0)
{
tempStr += "\t";
}
tempStr += dataGridView1.Rows[j].Cells[k].Value.ToString();
}
sw.WriteLine(tempStr);
}
sw.Close();
myStream.Close();
}
catch (Exception ex)
{
//MessageBox.Show(ex.ToString());
}
finally
{
sw.Close();
myStream.Close();
}
#endregion
이런 방법의 장점 은 내 보 내 는 것 이 비교적 빠 르 지만 엑셀 표 에 제목,글꼴 스타일 등 을 설정 할 수 없다 는 것 이다.왜냐하면 너 는 데이터 흐름 으로 엑셀 로 직접 내 보 내 는 것 이기 때문이다.네가 데이터 흐름 에 이런 스타일 을 설정 할 수 있 는 것 이 아니라면 나 는 아직 이런 능력 이 없다.어떤 형님 이 가르쳐 주 실 것 인가?헤헤두 번 째 방법 은 바로 하나의 종 류 를 쓰 는 것 이다.이런 종 류 는 EXCEL 을 직접 조작 하 는 것 이다.
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Text;
using System.Diagnostics;
using System.IO;
using Microsoft.Office.Interop.Excel;
namespace Excel
{
public class Export
{
/// <summary>
/// DataGridView Excel
/// </summary>
/// <param name="strCaption">Excel </param>
/// <param name="myDGV">DataGridView </param>
/// <returns>0: ;1:DataGridView ;2:Excel ;9999: </returns>
public int ExportExcel(string strCaption, DataGridView myDGV, SaveFileDialog saveFileDialog)
{
int result = 9999;
//
saveFileDialog.Filter = "Execl files (*.xls)|*.xls";
saveFileDialog.FilterIndex = 0;
saveFileDialog.RestoreDirectory = true;
//saveFileDialog.CreatePrompt = true;
saveFileDialog.Title = "Export Excel File";
if ( saveFileDialog.ShowDialog()== DialogResult.OK)
{
if (saveFileDialog.FileName == "")
{
MessageBox.Show(" !");
saveFileDialog.ShowDialog();
}
// , , ,
int ColIndex = 0;
int RowIndex = 0;
int ColCount = myDGV.ColumnCount;
int RowCount = myDGV.RowCount;
if (myDGV.RowCount == 0)
{
result = 1;
}
// Excel
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
if (xlApp == null)
{
result = 2;
}
try
{
// Excel
Microsoft.Office.Interop.Excel.Workbook xlBook = xlApp.Workbooks.Add(true);
Microsoft.Office.Interop.Excel.Worksheet xlSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlBook.Worksheets[1];
//
Microsoft.Office.Interop.Excel.Range range = xlSheet.get_Range(xlApp.Cells[1, 1], xlApp.Cells[1, ColCount]); // DataGridView
range.MergeCells = true;
xlApp.ActiveCell.FormulaR1C1 = strCaption;
xlApp.ActiveCell.Font.Size = 20;
xlApp.ActiveCell.Font.Bold = true;
xlApp.ActiveCell.HorizontalAlignment = Microsoft.Office.Interop.Excel.Constants.xlCenter;
//
object[,] objData = new object[RowCount + 1, ColCount];
//
foreach (DataGridViewColumn col in myDGV.Columns)
{
objData[RowIndex, ColIndex++] = col.HeaderText;
}
//
for (RowIndex = 1; RowIndex < RowCount; RowIndex++)
{
for (ColIndex = 0; ColIndex < ColCount; ColIndex++)
{
if (myDGV[ColIndex, RowIndex - 1].ValueType == typeof(string)
|| myDGV[ColIndex, RowIndex - 1].ValueType == typeof(DateTime))// DataGridView , string DataTime , " ";
{
objData[RowIndex, ColIndex] = "" + myDGV[ColIndex, RowIndex - 1].Value;
}
else
{
objData[RowIndex, ColIndex] = myDGV[ColIndex, RowIndex - 1].Value;
}
}
System.Windows.Forms.Application.DoEvents();
}
// Excel
range = xlSheet.get_Range(xlApp.Cells[2, 1], xlApp.Cells[RowCount, ColCount]);
range.Value2 = objData;
xlBook.Saved = true;
xlBook.SaveCopyAs(saveFileDialog.FileName);
}
catch (Exception err)
{
result = 9999;
}
finally
{
xlApp.Quit();
GC.Collect(); //
}
//
result = 0;
}
return result;
}
}
}
이 장점 은 스타일 같은 것 을 설정 할 수 있다 는 것 이다.단점 은 내 보 내기 속도 가 느 려 서...이상 두 가지 방법 은 모두 많은 재 료 를 참고 한 것 입 니 다.서로 공부 할 수 있 도록 여기에 쓰 세 요.
보충:두 번 째 방법 으로 엑셀 을 내 보 내 면 격식 적 인 변화 가 있 을 수 있 습 니 다.예 를 들 어 신분증 번 호 는 과학 계산법 에 따라 내 보 냈 습 니 다.원래 의 모델 이 아 닙 니 다.
개선 방법 은 엑셀 을 쓸 때 형식 설명 을 추가 하 는 것 입 니 다.range.NumberFormat Local="@";
엑셀
range = xlSheet.get_Range(xlApp.Cells[2, 1], xlApp.Cells[RowCount + 2, ColCount]);
range.NumberFormatLocal = "@";
range.Value2 = objData;
C\#중 DataGridView 에서 Excel 을 내 보 내 는 두 가지 방법 에 관 한 이 글 은 여기까지 소개 되 었 습 니 다.더 많은 관련 C\#DataGridView 에서 Excel 을 내 보 내 는 내용 은 우리 의 이전 글 을 검색 하거나 아래 의 관련 글 을 계속 찾 아 보 세 요.앞으로 도 많은 응원 부 탁 드 리 겠 습 니 다!
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
WebView2를 Visual Studio 2017 Express에서 사용할 수 있을 때까지Evergreen .Net Framework SDK 4.8 VisualStudio2017에서 NuGet을 사용하기 때문에 패키지 관리 방법을 packages.config 대신 PackageReference를 사용해야...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.