c# DataGridView导出到Excel,如果数据列数很多,格式就会乱 #region 导出成Excel
/// <summary> /// 另存新档按钮 /// </summary> public static void SaveAsExcel(DataGridView dg) //另存新档按钮 导出成Excel
{ SaveFileDialog saveFileDialog = new SaveFileDialog(); saveFileDialog.Filter = "Execl files (*.xls)|*.xls"; saveFileDialog.FilterIndex = 0; saveFileDialog.RestoreDirectory = true; saveFileDialog.CreatePrompt = true; saveFileDialog.Title = "Export Excel File To"; saveFileDialog.ShowDialog(); Stream myStream; myStream = saveFileDialog.OpenFile(); //StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding("gb2312")); StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0)); string str = ""; try
{
//写标题
for (int i = 0; i < dg.ColumnCount; i++)
{
if (i > 0)
{
str += "\t";
}
str += dg.Columns[i].HeaderText;
}
sw.WriteLine(str); //写内容
for (int j = 0; j < dg.Rows.Count; j++)
{
string tempStr = "";
for (int k = 0; k < dg.Columns.Count; k++)
{
if (k > 0)
{
tempStr += "\t";
}
tempStr += dg.Rows[j].Cells[k].Value.ToString();
}
sw.WriteLine(tempStr);
}
sw.Close();
myStream.Close();
}
catch (Exception e)
{
MessageBox.Show(e.GetBaseException().ToString());
}
finally
{
sw.Close();
myStream.Close();
}
}
#endregionC#ExcelDataGridView
/// <summary> /// 另存新档按钮 /// </summary> public static void SaveAsExcel(DataGridView dg) //另存新档按钮 导出成Excel
{ SaveFileDialog saveFileDialog = new SaveFileDialog(); saveFileDialog.Filter = "Execl files (*.xls)|*.xls"; saveFileDialog.FilterIndex = 0; saveFileDialog.RestoreDirectory = true; saveFileDialog.CreatePrompt = true; saveFileDialog.Title = "Export Excel File To"; saveFileDialog.ShowDialog(); Stream myStream; myStream = saveFileDialog.OpenFile(); //StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding("gb2312")); StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0)); string str = ""; try
{
//写标题
for (int i = 0; i < dg.ColumnCount; i++)
{
if (i > 0)
{
str += "\t";
}
str += dg.Columns[i].HeaderText;
}
sw.WriteLine(str); //写内容
for (int j = 0; j < dg.Rows.Count; j++)
{
string tempStr = "";
for (int k = 0; k < dg.Columns.Count; k++)
{
if (k > 0)
{
tempStr += "\t";
}
tempStr += dg.Rows[j].Cells[k].Value.ToString();
}
sw.WriteLine(tempStr);
}
sw.Close();
myStream.Close();
}
catch (Exception e)
{
MessageBox.Show(e.GetBaseException().ToString());
}
finally
{
sw.Close();
myStream.Close();
}
}
#endregionC#ExcelDataGridView
还有你再使用别人代码之前最好自己先理解了之后才使用,不然出现了问题完全不知道如何解决,而不是自己放到论坛中直接获得答案了,你最好自己调试下,之后下次出现类似的问题才能解决,如果你一遇到问题就放到论坛中希望别人给你完全解决掉,然后就不管,下次遇到了还是不会,所以我对你的意见是——首先要自己先调试下,论坛中只能给你思路或者一些示例代码,主要还要靠自己消化
http://download.csdn.net/detail/jx_521/5819725
我是用aspose.cells.dll做的,看看能否帮助你。