winfrom中DataGridView导出Excel问题(0x800A03EC)
- C# code
#region DataGridView导出到Excel,有一定的判断性 /// <summary> ///方法,导出DataGridView中的数据到Excel文件 /// </summary> /// <remarks> /// add com "Microsoft Excel 11.0 Object Library" /// using Excel=Microsoft.Office.Interop.Excel; /// using System.Reflection; /// </remarks> /// <param name= "dgv"> DataGridView </param> public void DataGridViewToExcel(DataGridView dgv) { #region 验证可操作性 //申明保存对话框 SaveFileDialog dlg = new SaveFileDialog(); //默然文件后缀 dlg.DefaultExt = "xls "; //文件后缀列表 dlg.Filter = "EXCEL文件(*.XLS)|*.xls "; //默然路径是系统当前路径 dlg.InitialDirectory = Directory.GetCurrentDirectory(); //打开保存对话框 if (dlg.ShowDialog() == DialogResult.Cancel) return; //返回文件路径 string fileNameString = dlg.FileName; //验证strFileName是否为空或值无效 if (fileNameString.Trim() == " ") { return; } //定义表格内数据的行数和列数 int rowscount = dgv.Rows.Count; int colscount = dgv.Columns.Count; //行数必须大于0 if (rowscount <= 0) { MessageBox.Show("没有数据可供保存 ", "提示 ", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } //列数必须大于0 if (colscount <= 0) { MessageBox.Show("没有数据可供保存 ", "提示 ", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } //行数不可以大于65536 if (rowscount > 65536) { MessageBox.Show("数据记录数太多(最多不能超过65536条),不能保存 ", "提示 ", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } //列数不可以大于255 if (colscount > 255) { MessageBox.Show("数据记录行数太多,不能保存 ", "提示 ", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } //验证以fileNameString命名的文件是否存在,如果存在删除它 FileInfo file = new FileInfo(fileNameString); if (file.Exists) { try { file.Delete(); } catch (Exception error) { MessageBox.Show(error.Message, "删除失败 ", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } } #endregion Microsoft.Office.Interop.Excel.Application objExcel = null; Microsoft.Office.Interop.Excel.Workbook objWorkbook = null; Microsoft.Office.Interop.Excel.Worksheet objsheet = null; try { //申明对象 objExcel = new Microsoft.Office.Interop.Excel.Application(); objWorkbook = objExcel.Workbooks.Add(Missing.Value); objsheet = (Microsoft.Office.Interop.Excel.Worksheet)objWorkbook.ActiveSheet; //设置EXCEL不可见 objExcel.Visible = false; dgv.Columns[0].Visible = false; dgv.Columns[1].Visible = false; //向Excel中写入表格的表头 int displayColumnsCount = 1; string[] HeaderText = {"铲板号","箱号","工程号","产品名称","Code","YN","版本号","扫描时间","员工"}; for (int i = 0; i <= dgv.ColumnCount - 1; i++) { if (dgv.Columns[i].Visible == true) { objExcel.Cells[1, displayColumnsCount] = HeaderText[i]; displayColumnsCount++; } } //设置进度条 //tempProgressBar.Refresh(); //tempProgressBar.Visible = true; //tempProgressBar.Minimum=1; //tempProgressBar.Maximum=dgv.RowCount; //tempProgressBar.Step=1; //向Excel中逐行逐列写入表格中的数据 for (int row = 0; row <= dgv.RowCount - 1; row++) { displayColumnsCount = 1; for (int col = 0; col < colscount; col++) { if (dgv.Columns[col].Visible == true) { try { if (col == 6) { string date = "'" + dgv.Rows[row].Cells[col].Value.ToString().Trim(); objExcel.Cells[row + 2, displayColumnsCount] = string.Format("{0}-{1}-{2} {3}:{4}:{5}", date.Substring(0, 5), date.Substring(5, 2), date.Substring(7, 2), date.Substring(9, 2), date.Substring(11, 2), date.Substring(13, 2)); displayColumnsCount++; } else { objExcel.Cells[row + 2, displayColumnsCount] = "" + dgv.Rows[row].Cells[col].Value.ToString().Trim(); displayColumnsCount++; } } catch (Exception) { throw; } } } } //保存文件 //objWorkbook.SaveAs(fileNameString, Missing.Value, Missing.Value, Missing.Value, Missing.Value, // Missing.Value, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Missing.Value, Missing.Value, Missing.Value, // Missing.Value, Missing.Value); objWorkbook.SaveAs(fileNameString, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); } catch (Exception error) { MessageBox.Show(error.Message, "警告 ", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } finally { //关闭Excel应用 if (objWorkbook != null) objWorkbook.Close(Missing.Value, Missing.Value, Missing.Value); if (objExcel.Workbooks != null) objExcel.Workbooks.Close(); if (objExcel != null) objExcel.Quit(); objsheet = null; objWorkbook = null; objExcel = null; } MessageBox.Show(fileNameString + "\n\n导出完毕! ", "提示 ", MessageBoxButtons.OK, MessageBoxIcon.Information); } #endregion
报错:
错误地方:
objWorkbook.SaveAs(fileNameString, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
求解,
[解决办法]
- C# code
using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;using Microsoft.Office.Interop.Excel;namespace WindowsFormsApplication2{ public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { string fileName = "c:\\abc.xls"; Microsoft.Office.Interop.Excel.Application excel = new ApplicationClass(); _Workbook myWorkBook; myWorkBook = excel.Workbooks.Add(true); excel.Cells[1, 1] = "ABC"; myWorkBook.SaveCopyAs(fileName); myWorkBook.Close(false, null, null); System.Runtime.InteropServices.Marshal.ReleaseComObject(myWorkBook); System.Runtime.InteropServices.Marshal.ReleaseComObject(excel); } }}
[解决办法]
http://blog.sina.com.cn/s/blog_6248dc000100f832.html
这个问题我也遇到过,没能够解决,后来换代码了
[解决办法]
发错链接了,那个找不到了。你参考我的代码,导出datagridview到csv。原理一样的
- C# code
private bool ExportToTxt(DataGridView dgv, ProgressBar pb) { SaveFileDialog dlg = new SaveFileDialog(); dlg.Filter = "文本文件(*.txt)|*.txt"; dlg.FilterIndex = 0; dlg.RestoreDirectory = true; dlg.CreatePrompt = true; dlg.Title = "保存为文本文件"; if (dlg.ShowDialog() == DialogResult.OK) { Stream myStream; myStream = dlg.OpenFile(); StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0)); string columnTitle = ""; try { //写入列标题 for (int i = 0; i < dgv.ColumnCount; i++) { if (i > 0) { columnTitle += ","; } columnTitle += dgv.Columns[i].HeaderText; } columnTitle.Remove(columnTitle.Length - 1); sw.WriteLine(columnTitle); //写入列内容 for (int j = 0; j < dgv.Rows.Count; j++) { string columnValue = ""; pb.Value = j * 100 / dgv.Rows.Count; for (int k = 0; k < dgv.Columns.Count; k++) { if (k > 0) { columnValue += "\t"; } if (dgv.Rows[j].Cells[k].Value == null) { columnValue += ""; } else { string m = dgv.Rows[j].Cells[k].Value.ToString().Trim(); columnValue += m.Replace("\t", ""); } } columnValue.Remove(columnValue.Length - 1); sw.WriteLine(columnValue); } sw.Close(); myStream.Close(); MessageBox.Show("完成!"); } catch (Exception e) { MessageBox.Show(e.ToString()); return false; } finally { sw.Close(); myStream.Close(); } return true; } else { return false; } }
[解决办法]
楼主你到底是objWorkbook.SaveAs报错
还是行列计算错误,
你先把问题搞清楚
我在5、6楼贴出的代码是告诉你用myWorkBook.SaveCopyAs(fileName)可以省去你objWorkbook.SaveAs的那一大堆Type.Missing,而且不报错
你也可以把全部列导出来,把那些要隐藏的列在Excel里设为宽度为0
[解决办法]
- C# code
namespace Common{ /// <summary> /// 操作EXCEL导出数据报表的类 /// </summary> public class DataToExcel { public DataToExcel() { } #region 操作EXCEL的一个类(需要Excel.dll支持) private int titleColorindex = 15; /// <summary> /// 标题背景色 /// </summary> public int TitleColorIndex { set { titleColorindex = value; } get { return titleColorindex; } } private DateTime beforeTime; //Excel启动之前时间 private DateTime afterTime; //Excel启动之后时间 #region 创建一个Excel示例 /// <summary> /// 创建一个Excel示例 /// </summary> public void CreateExcel() { Excel.Application excel = new Excel.Application(); excel.Application.Workbooks.Add(true); excel.Cells[1, 1] = "第1行第1列"; excel.Cells[1, 2] = "第1行第2列"; excel.Cells[2, 1] = "第2行第1列"; excel.Cells[2, 2] = "第2行第2列"; excel.Cells[3, 1] = "第3行第1列"; excel.Cells[3, 2] = "第3行第2列"; //保存 excel.ActiveWorkbook.SaveAs("./tt.xls", XlFileFormat.xlExcel9795, null, null, false, false, Excel.XlSaveAsAccessMode.xlNoChange, null, null, null, null, null); //打开显示 excel.Visible = true; // excel.Quit(); // excel=null; // GC.Collect();//垃圾回收 } #endregion #region 将DataTable的数据导出显示为报表 /// <summary> /// 将DataTable的数据导出显示为报表 /// </summary> /// <param name="dt">要导出的数据</param> /// <param name="strTitle">导出报表的标题</param> /// <param name="FilePath">保存文件的路径</param> /// <returns></returns> public string OutputExcel(System.Data.DataTable dt, string strTitle, string FilePath) { beforeTime = DateTime.Now; Excel.Application excel; Excel._Workbook xBk; Excel._Worksheet xSt; int rowIndex = 4; int colIndex = 1; excel = new Excel.ApplicationClass(); xBk = excel.Workbooks.Add(true); xSt = (Excel._Worksheet)xBk.ActiveSheet; //取得列标题 foreach (DataColumn col in dt.Columns) { colIndex++; excel.Cells[4, colIndex] = col.ColumnName; //设置标题格式为居中对齐 xSt.get_Range(excel.Cells[4, colIndex], excel.Cells[4, colIndex]).Font.Bold = true; xSt.get_Range(excel.Cells[4, colIndex], excel.Cells[4, colIndex]).HorizontalAlignment = Excel.XlVAlign.xlVAlignCenter; xSt.get_Range(excel.Cells[4, colIndex], excel.Cells[4, colIndex]).Select(); xSt.get_Range(excel.Cells[4, colIndex], excel.Cells[4, colIndex]).Interior.ColorIndex = titleColorindex;//19;//设置为浅黄色,共计有56种 } //取得表格中的数据 foreach (DataRow row in dt.Rows) { rowIndex++; colIndex = 1; foreach (DataColumn col in dt.Columns) { colIndex++; if (col.DataType == System.Type.GetType("System.DateTime")) { excel.Cells[rowIndex, colIndex] = (Convert.ToDateTime(row[col.ColumnName].ToString())).ToString("yyyy-MM-dd"); xSt.get_Range(excel.Cells[rowIndex, colIndex], excel.Cells[rowIndex, colIndex]).HorizontalAlignment = Excel.XlVAlign.xlVAlignCenter;//设置日期型的字段格式为居中对齐 } else if (col.DataType == System.Type.GetType("System.String")) { excel.Cells[rowIndex, colIndex] = "'" + row[col.ColumnName].ToString(); xSt.get_Range(excel.Cells[rowIndex, colIndex], excel.Cells[rowIndex, colIndex]).HorizontalAlignment = Excel.XlVAlign.xlVAlignCenter;//设置字符型的字段格式为居中对齐 } else { excel.Cells[rowIndex, colIndex] = row[col.ColumnName].ToString(); } } } //加载一个合计行 int rowSum = rowIndex + 1; int colSum = 2; excel.Cells[rowSum, 2] = "合计"; xSt.get_Range(excel.Cells[rowSum, 2], excel.Cells[rowSum, 2]).HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter; //设置选中的部分的颜色 xSt.get_Range(excel.Cells[rowSum, colSum], excel.Cells[rowSum, colIndex]).Select(); //xSt.get_Range(excel.Cells[rowSum,colSum],excel.Cells[rowSum,colIndex]).Interior.ColorIndex =Assistant.GetConfigInt("ColorIndex");// 1;//设置为浅黄色,共计有56种 //取得整个报表的标题 excel.Cells[2, 2] = strTitle; //设置整个报表的标题格式 xSt.get_Range(excel.Cells[2, 2], excel.Cells[2, 2]).Font.Bold = true; xSt.get_Range(excel.Cells[2, 2], excel.Cells[2, 2]).Font.Size = 22; //设置报表表格为最适应宽度 xSt.get_Range(excel.Cells[4, 2], excel.Cells[rowSum, colIndex]).Select(); xSt.get_Range(excel.Cells[4, 2], excel.Cells[rowSum, colIndex]).Columns.AutoFit(); //设置整个报表的标题为跨列居中 xSt.get_Range(excel.Cells[2, 2], excel.Cells[2, colIndex]).Select(); xSt.get_Range(excel.Cells[2, 2], excel.Cells[2, colIndex]).HorizontalAlignment = Excel.XlHAlign.xlHAlignCenterAcrossSelection; //绘制边框 xSt.get_Range(excel.Cells[4, 2], excel.Cells[rowSum, colIndex]).Borders.LineStyle = 1; xSt.get_Range(excel.Cells[4, 2], excel.Cells[rowSum, 2]).Borders[Excel.XlBordersIndex.xlEdgeLeft].Weight = Excel.XlBorderWeight.xlThick;//设置左边线加粗 xSt.get_Range(excel.Cells[4, 2], excel.Cells[4, colIndex]).Borders[Excel.XlBordersIndex.xlEdgeTop].Weight = Excel.XlBorderWeight.xlThick;//设置上边线加粗 xSt.get_Range(excel.Cells[4, colIndex], excel.Cells[rowSum, colIndex]).Borders[Excel.XlBordersIndex.xlEdgeRight].Weight = Excel.XlBorderWeight.xlThick;//设置右边线加粗 xSt.get_Range(excel.Cells[rowSum, 2], excel.Cells[rowSum, colIndex]).Borders[Excel.XlBordersIndex.xlEdgeBottom].Weight = Excel.XlBorderWeight.xlThick;//设置下边线加粗 afterTime = DateTime.Now; //显示效果 //excel.Visible=true; //excel.Sheets[0] = "sss"; ClearFile(FilePath); string filename = DateTime.Now.ToString("yyyyMMddHHmmssff") + ".xls"; excel.ActiveWorkbook.SaveAs(FilePath + filename, Excel.XlFileFormat.xlExcel9795, null, null, false, false, Excel.XlSaveAsAccessMode.xlNoChange, null, null, null, null, null); //wkbNew.SaveAs strBookName; //excel.Save(strExcelFileName); #region 结束Excel进程 //需要对Excel的DCOM对象进行配置:dcomcnfg //excel.Quit(); //excel=null; xBk.Close(null, null, null); excel.Workbooks.Close(); excel.Quit(); //注意:这里用到的所有Excel对象都要执行这个操作,否则结束不了Excel进程 // if(rng != null) // { // System.Runtime.InteropServices.Marshal.ReleaseComObject(rng); // rng = null; // } // if(tb != null) // { // System.Runtime.InteropServices.Marshal.ReleaseComObject(tb); // tb = null; // } if (xSt != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(xSt); xSt = null; } if (xBk != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(xBk); xBk = null; } if (excel != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(excel); excel = null; } GC.Collect();//垃圾回收 #endregion return filename; }
[解决办法]
续
- C# code
#endregion
#region Kill Excel进程
/// <summary>
/// 结束Excel进程
/// </summary>
public void KillExcelProcess()
{
Process[] myProcesses;
DateTime startTime;
myProcesses = Process.GetProcessesByName("Excel");
//得不到Excel进程ID,暂时只能判断进程启动时间
foreach (Process myProcess in myProcesses)
{
startTime = myProcess.StartTime;
if (startTime > beforeTime && startTime < afterTime)
{
myProcess.Kill();
}
}
}
#endregion
#endregion
#region 将DataTable的数据导出显示为报表(不使用Excel对象,使用COM.Excel)
#region 使用示例
public static void GridViewToExcel(DataSet MyData, Hashtable nameList,string ReportTitle)
{
string FilePath = System.Web.HttpContext.Current.Server.MapPath("../") + "ReportFile\\";
//利用excel对象
DataToExcel dte = new DataToExcel();
string filename = "";
try
{
if (MyData.Tables[0].Rows.Count > 0)
{
filename = dte.DataExcel(MyData.Tables[0], ReportTitle, FilePath, nameList);
}
}
catch
{}
if (filename != "")
{
System.Web.HttpContext.Current.Response.Redirect("../ReportFile/" + filename, true);
}
}
#endregion
/// <summary>
/// 将DataTable的数据导出显示为报表(不使用Excel对象)
/// </summary>
/// <param name="dt">数据DataTable </param>
/// <param name="strTitle">标题 </param>
/// <param name="FilePath">生成文件的路径 </param>
/// <param name="nameList"> </param>
/// <returns> </returns>
public string DataExcel(System.Data.DataTable dt, string strTitle, string FilePath, Hashtable nameList)
{
COM.Excel.cExcelFile excel = new COM.Excel.cExcelFile();
ClearFile(FilePath);
string filename = DateTime.Now.ToString("yyyyMMddHHmmssff") + ".xls";
excel.CreateFile(FilePath + filename);
excel.PrintGridLines = false;
COM.Excel.cExcelFile.MarginTypes mt1 = COM.Excel.cExcelFile.MarginTypes.xlsTopMargin;
COM.Excel.cExcelFile.MarginTypes mt2 = COM.Excel.cExcelFile.MarginTypes.xlsLeftMargin;
COM.Excel.cExcelFile.MarginTypes mt3 = COM.Excel.cExcelFile.MarginTypes.xlsRightMargin;
COM.Excel.cExcelFile.MarginTypes mt4 = COM.Excel.cExcelFile.MarginTypes.xlsBottomMargin;
double height = 1.5;
excel.SetMargin(ref mt1, ref height);
excel.SetMargin(ref mt2, ref height);
excel.SetMargin(ref mt3, ref height);
excel.SetMargin(ref mt4, ref height);
COM.Excel.cExcelFile.FontFormatting ff = COM.Excel.cExcelFile.FontFormatting.xlsNoFormat;
string font = "宋体";
short fontsize = 9;
excel.SetFont(ref font, ref fontsize, ref ff);
byte b1 = 1,
b2 = 12;
short s3 = 12;
excel.SetColumnWidth(ref b1, ref b2, ref s3);
string header = "页眉";
string footer = "页脚";
excel.SetHeader(ref header);
excel.SetFooter(ref footer);
COM.Excel.cExcelFile.ValueTypes vt = COM.Excel.cExcelFile.ValueTypes.xlsText;
COM.Excel.cExcelFile.CellFont cf = COM.Excel.cExcelFile.CellFont.xlsFont0;
COM.Excel.cExcelFile.CellAlignment ca = COM.Excel.cExcelFile.CellAlignment.xlsCentreAlign;
COM.Excel.cExcelFile.CellHiddenLocked chl = COM.Excel.cExcelFile.CellHiddenLocked.xlsNormal;
// 报表标题
int cellformat = 1;
//int rowindex = 1,colindex = 3;
//object title = (object)strTitle;
//excel.WriteValue(ref vt, ref cf, ref ca, ref chl,ref rowindex,ref colindex,ref title,ref cellformat);
int rowIndex = 1;//起始行
int colIndex = 0;
//取得列标题
foreach (DataColumn colhead in dt.Columns)
{
colIndex++;
string name = colhead.ColumnName.Trim();
object namestr = (object)name;
IDictionaryEnumerator Enum = nameList.GetEnumerator();
while (Enum.MoveNext())
{
if (Enum.Key.ToString().Trim() == name)
{
namestr = Enum.Value;
}
}
excel.WriteValue(ref vt, ref cf, ref ca, ref chl, ref rowIndex, ref colIndex, ref namestr, ref cellformat);
}
//取得表格中的数据
foreach (DataRow row in dt.Rows)
{
rowIndex++;
colIndex = 0;
foreach (DataColumn col in dt.Columns)
{
colIndex++;
if (col.DataType == System.Type.GetType("System.DateTime"))
{
object str = (object)(Convert.ToDateTime(row[col.ColumnName].ToString())).ToString("yyyy-MM-dd"); ;
excel.WriteValue(ref vt, ref cf, ref ca, ref chl, ref rowIndex, ref colIndex, ref str, ref cellformat);
}
else
{
object str = (object)row[col.ColumnName].ToString();
excel.WriteValue(ref vt, ref cf, ref ca, ref chl, ref rowIndex, ref colIndex, ref str, ref cellformat);
}
}
}
int ret = excel.CloseFile();
//if(ret!=0)
//{
////MessageBox.Show(this,"Error!");
//}
//else
//{
////MessageBox.Show(this,"请打开文件c:\\test.xls!");
//}
return filename;
}
#endregion
#region 清理过时的Excel文件
private void ClearFile(string FilePath)
{
String[] Files = System.IO.Directory.GetFiles(FilePath);
if (Files.Length > 10)
{
for (int i = 0; i < 10; i++)
{
try
{
System.IO.File.Delete(Files[i]);
}
catch
{
}
}
}
}
#endregion
}
}
[解决办法]
看看Excel引用的版本,如果引用的版本和你现在有电脑的上版本不同,会报这样的错误,至少我是这样的. 我的情况.引用Excel2003,程序所在的电脑上只有97,保存报"尝试读取或写入受保护的内存。这通常指示其他内存已损坏"错误. 或许 是因为Excel2003 与 97 保存时参数不同,Microsoft才报这样的错误.只是猜测.
[解决办法]
这是我写过的一个导出到Excel的代码:
lz可以看看:
- C# code
#region 导出信息(公共方法) public void Export(DataGridView dgvExport,string strFileName,string strTips) /// <summary> /// 导出信息(公共方法) /// </summary> /// <param name="dgvExport">datagridview控件中的数据</param> /// <param name="strFileName">文件名</param> /// <param name="strTips">提示信息</param> public void Export(DataGridView dgvExport,string strFileName,string strTips) { //判断控件中是否有数据 if (dgvExport.Rows.Count > 0) { //初始化导出对话框 SaveFileDialog saveFileDialog = new SaveFileDialog(); saveFileDialog.DefaultExt = "xls"; saveFileDialog.Filter = "EXCEL文件(*.XLS)|*.xls"; saveFileDialog.FilterIndex = 0; saveFileDialog.FileName = strFileName; saveFileDialog.RestoreDirectory = true; saveFileDialog.CreatePrompt = true; saveFileDialog.Title = "导出到EXCEL"; //弹出保存文件的对话框 saveFileDialog.ShowDialog(); //文件名为空的话,返回 if (saveFileDialog.FileName == "") return; //数据流声明 Stream myStream; StreamWriter swOut; //定义列名字符串 string strColumnText; //初始化对象 myStream = saveFileDialog.OpenFile(); swOut = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0)); strColumnText = ""; //若控件中有数据,则执行操作 if (dgvExport.RowCount > 0) { //读取信息 try { //初始化列 for (int i = 0; i < dgvExport.ColumnCount; i++) { //只导出控件中可见的数据 if (dgvExport.Columns[i].Visible == true) { if (i > 0) { //制表符 strColumnText += "\t"; } //获取列名字符串作为Excel文件中的列名 strColumnText += dgvExport.Columns[i].HeaderText; } } //输出strColumnText swOut.WriteLine(strColumnText); //读取每一条数据的内容 for (int j = 0; j < dgvExport.Rows.Count; j++) { string tempStr = ""; for (int k = 0; k < dgvExport.Columns.Count; k++) { //只导出控件中可见的数据 if (dgvExport.Columns[k].Visible == true) { if (k > 0) { //制表符 tempStr += "\t"; } //获取控件中非空单元格中的信息 if(dgvExport.Rows[j].Cells[k].Value!=null) tempStr += dgvExport.Rows[j].Cells[k].Value.ToString(); } } //输出信息 swOut.WriteLine(tempStr); } } //捕获异常 catch (Exception ex) { MessageBox.Show(ex.ToString()); } finally { //关闭数据流 swOut.Close(); myStream.Close(); } } } //控件中没有信息,给出提示 else { MessageBox.Show(strTips, "操作提示", MessageBoxButtons.OK, MessageBoxIcon.Information); } } #endregion
[解决办法]
你还是先导成TXT,看是不是数据的问题。
如果txt是正确的,就是EXCEL的问题,有一些东西是需要关闭的。