日期:2014-05-18 浏览次数:21083 次
public bool ExportDataGridview(DataGridView gridView, bool isShowExcele) { if (gridView.Rows.Count == 0) { return false; } //建立Excel对象 Excel.Application excel = new Excel.Application(); excel.Application.Workbooks.Add(true); excel.Visible = isShowExcele; int rowCount = gridView.Rows.Count; int colCount = gridView.Columns.Count; object[,] dataArray = new object[rowCount, colCount]; for (int i = 0; i < gridView.ColumnCount; i++) { dataArray[0, i] = gridView.Columns[i].HeaderText; } for (int i = 0; i < rowCount-1; i++) { for (int j = 0; j < colCount; j++) { if (gridView[j, i].Value.GetType() == typeof(string)) { dataArray[i+1, j] = "'" + gridView[j,i].Value.ToString();//在字符型的变量前加' } else { dataArray[i+1, j] = gridView[j, i].Value.ToString(); } } } excel.get_Range("A1", excel.Cells[rowCount, colCount]).Value2 = dataArray; excel.Cells.EntireColumn.AutoFit(); return true; } private void button1_Click(object sender, EventArgs e) { this.ExportDataGridview(dataGridView1, true); }
------解决方案--------------------
写入单元格的时候,前面加一个单引号
------解决方案--------------------
导出用 XML 然后改成XLS就行了.
//---将表格写成XML文件---不用样式表
public static void ExportXls(DataGridView dgv,string filename)
{
try
{
filename = filename.Replace("xls", "xml"); ;
System.Xml.XmlTextWriter writer = null;
writer = new System.Xml.XmlTextWriter(filename, null);
////为使文件易读,使用缩进
writer.Formatting = System.Xml.Formatting.Indented;
////写XML声明
writer.WriteStartDocument(true);
//写入注释
// writer.WriteComment("xml To xls = xml文件转换成xls文件");
writer.WriteStartElement("Workbook");
writer.WriteAttributeString("xmlns:msxsl", "urn:schemas-microsoft-com:xslt");
writer.WriteAttributeString("xmlns:user", "urn:my-scripts");
writer.WriteAttributeString("xmlns", "urn:schemas-microsoft-com:office:spreadsheet");
writer.WriteAttributeString("xmlns:o", "urn:schemas-microsoft-com:office:office");
writer.WriteAttributeString("xmlns:x", "urn:schemas-microsoft-com:office:excel");
writer.WriteAttributeString("xmlns:ss", "urn:schemas-microsoft-com:office:spreadsheet");
writer.WriteAttributeString("xmlns:html", "http://www.w3.org/TR/REC-html40");
//--单元格格式---
writer.WriteStartElement("Styles");
writer.WriteStartElement("Style");
writer.WriteAttributeString("ss:ID", "s0");
//--以下是对齐样式
writer.WriteStartElement("Alignment");