我們一般用的方法是將表遍歷一遍,然後寫入到excel中,主要程式碼如下:
///<summary>
///指定檔名稱、表名、DataGridView匯出DataGridView中的資料到Excel中
///</summary>
///<paramname="location">輸出檔案的位置</param>
///<paramname="tableName">表名</param>
///<paramname="dt">DataGridView名稱</param>
publicvoidGridViewToExcel(stringlocation,stringtableName,DataGridViewdt)
{
StreammyStream;
myStream=File.Open(location,FileMode.Create);
//StreamWritersw=newStreamWriter(myStream,System.Text.Encoding.GetEncoding("gb2312"));
StreamWritersw=newStreamWriter(myStream,System.Text.Encoding.GetEncoding(-0));
stringstr="";
intm=0;
try
//寫標題
for(inti=0;i<dt.ColumnCount;i++)
if(dt.Columns[i].Visible==false)
continue;
}
else
str+=dt.Columns[i].HeaderText+"\t";
//stringaa=str.Substring(0,str.Length-1);
sw.WriteLine(str.Substring(0,str.Length-1));
//寫內容
for(intj=0;j<dt.Rows.Count;j++)
if(dt.Rows[j].Visible==true)
stringtempStr="";
for(intk=0;k<dt.Columns.Count;k++)
if(dt.Columns[k].Visible==false)
tempStr+=dt.Rows[j].Cells[k].Value.ToString()+"\t";
sw.WriteLine(tempStr.Substring(0,tempStr.Length-1));
sw.Close();
myStream.Close();
catch(Exceptione)
MessageBox.Show(e.ToString());
finally
我們一般用的方法是將表遍歷一遍,然後寫入到excel中,主要程式碼如下:
///<summary>
///指定檔名稱、表名、DataGridView匯出DataGridView中的資料到Excel中
///</summary>
///<paramname="location">輸出檔案的位置</param>
///<paramname="tableName">表名</param>
///<paramname="dt">DataGridView名稱</param>
publicvoidGridViewToExcel(stringlocation,stringtableName,DataGridViewdt)
{
StreammyStream;
myStream=File.Open(location,FileMode.Create);
//StreamWritersw=newStreamWriter(myStream,System.Text.Encoding.GetEncoding("gb2312"));
StreamWritersw=newStreamWriter(myStream,System.Text.Encoding.GetEncoding(-0));
stringstr="";
intm=0;
try
{
//寫標題
for(inti=0;i<dt.ColumnCount;i++)
{
if(dt.Columns[i].Visible==false)
{
continue;
}
else
{
str+=dt.Columns[i].HeaderText+"\t";
}
}
//stringaa=str.Substring(0,str.Length-1);
sw.WriteLine(str.Substring(0,str.Length-1));
//寫內容
for(intj=0;j<dt.Rows.Count;j++)
{
if(dt.Rows[j].Visible==true)
{
stringtempStr="";
for(intk=0;k<dt.Columns.Count;k++)
{
if(dt.Columns[k].Visible==false)
{
continue;
}
else
{
tempStr+=dt.Rows[j].Cells[k].Value.ToString()+"\t";
}
}
sw.WriteLine(tempStr.Substring(0,tempStr.Length-1));
}
}
sw.Close();
myStream.Close();
}
catch(Exceptione)
{
MessageBox.Show(e.ToString());
}
finally
{
sw.Close();
myStream.Close();
}
}