大家好~!我这里有个winform项目,用C#写的。
需求是这样的,首先是把EXCEL2003文件导入到datagridview里(已经实现了),
然后,又从datagridview里导出EXCEL2003文件~!导出时候,我用的是GemBox.ExcelLite这个控件。但是这个不支持导出excel2007格式
我想问的是,
1.从datagridview导出EXCEL2007格式的,请问怎么办?2.还有,就是我电脑假如没有装OFFICE2003或者OFFICE2007,我能否导出呢?怎么做?这2个问题困扰我很久,希望大家能帮我解决下,我将感激不尽~!谢谢~!
需求是这样的,首先是把EXCEL2003文件导入到datagridview里(已经实现了),
然后,又从datagridview里导出EXCEL2003文件~!导出时候,我用的是GemBox.ExcelLite这个控件。但是这个不支持导出excel2007格式
我想问的是,
1.从datagridview导出EXCEL2007格式的,请问怎么办?2.还有,就是我电脑假如没有装OFFICE2003或者OFFICE2007,我能否导出呢?怎么做?这2个问题困扰我很久,希望大家能帮我解决下,我将感激不尽~!谢谢~!
{ Microsoft.Office.Interop.Excel.ApplicationClass MyExcel = new Microsoft.Office.Interop.Excel.ApplicationClass();
MyExcel.Visible = true;
if (MyExcel == null)
{
MessageBox.Show("EXCEL无法启动!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
int rowcount = 0;
int columncount = 0;
MyExcel.Application.Workbooks.Add(true);
columncount = this.dataGridView1.ColumnCount;
rowcount = this.dataGridView1.RowCount;
for (int m = 0; m < columncount; m++)
{
MyExcel.Cells[1, m+1] = this.dataGridView1.Columns[m].HeaderText;
}
for (int i = 0; i < rowcount; i++)
{
for (int j = 0; j < columncount; j++)
{
MyExcel.Cells[i + 2, j+1] = this.dataGridView1[j, i].Value.ToString();
}
} }//竖着导出 private void toolStripButton2_Click(object sender, EventArgs e)
{
Microsoft.Office.Interop.Excel.ApplicationClass MyExcel = new Microsoft.Office.Interop.Excel.ApplicationClass();
MyExcel.Visible = true;
if (MyExcel == null)
{
MessageBox.Show("EXCEL无法启动!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
int rowcount = 0;
int columncount = 0;
MyExcel.Application.Workbooks.Add(true);
columncount = this.dataGridView1.ColumnCount;
rowcount = this.dataGridView1.RowCount;
for (int m = 0; m < columncount; m++)
{
MyExcel.Cells[1 + m, 1] = this.dataGridView1.Columns[m].HeaderText;
}
for (int i = 0; i < rowcount; i++)
{
for (int j = 0; j < columncount; j++)
{
MyExcel.Cells[j + 1, i + 2] = this.dataGridView1[j, i].Value.ToString();
}
} }
{ Microsoft.Office.Interop.Excel.ApplicationClass MyExcel = new Microsoft.Office.Interop.Excel.ApplicationClass();
MyExcel.Visible = true;
if (MyExcel == null)
{
MessageBox.Show("EXCEL无法启动!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
int rowcount = 0;
int columncount = 0;
MyExcel.Application.Workbooks.Add(true);
columncount = this.dataGridView1.ColumnCount;
rowcount = this.dataGridView1.RowCount;
for (int m = 0; m < columncount; m++)
{
MyExcel.Cells[1, m+1] = this.dataGridView1.Columns[m].HeaderText;
}
for (int i = 0; i < rowcount; i++)
{
for (int j = 0; j < columncount; j++)
{
MyExcel.Cells[i + 2, j+1] = this.dataGridView1[j, i].Value.ToString();
}
} }//竖着导出 private void toolStripButton2_Click(object sender, EventArgs e)
{
Microsoft.Office.Interop.Excel.ApplicationClass MyExcel = new Microsoft.Office.Interop.Excel.ApplicationClass();
MyExcel.Visible = true;
if (MyExcel == null)
{
MessageBox.Show("EXCEL无法启动!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
int rowcount = 0;
int columncount = 0;
MyExcel.Application.Workbooks.Add(true);
columncount = this.dataGridView1.ColumnCount;
rowcount = this.dataGridView1.RowCount;
for (int m = 0; m < columncount; m++)
{
MyExcel.Cells[1 + m, 1] = this.dataGridView1.Columns[m].HeaderText;
}
for (int i = 0; i < rowcount; i++)
{
for (int j = 0; j < columncount; j++)
{
MyExcel.Cells[j + 1, i + 2] = this.dataGridView1[j, i].Value.ToString();
}
} }
/// <summary>
/// 在磁盘上创建一个临时的excel文件
/// </summary>
private void CreateExcelFile(string filePath)
{
if (File.Exists(filePath))
{
File.Delete(filePath);
} OleDbConnection oleDbConn = new OleDbConnection();
OleDbCommand oleDbCmd = new OleDbCommand();
string sSql = ""; try
{
//设置导出所有数据
gvShowInfo.AllowPaging = false; //清除分页
gvShowInfo.AllowSorting = false; //清除排序
this.gvShowInfo.DataBind(); //打开Microsoft.Jet.OleDb.4.0连接
oleDbConn.ConnectionString = "Provider=Microsoft.Jet.OleDb.4.0;Data Source=" + filePath + @";Extended ProPerties=""Excel 8.0;HDR=Yes;""";
oleDbConn.Open();
oleDbCmd.CommandType = CommandType.Text;
oleDbCmd.Connection = oleDbConn; //写列名
sSql = "CREATE TABLE sheet1(";
for (int i = 0; i < this.gvShowInfo.Columns.Count; i++)
{
if (i < this.gvShowInfo.Columns.Count - 1)
{
sSql += this.gvShowInfo.Columns[i].HeaderText + " Text(100),";
}
else
{
sSql += this.gvShowInfo.Columns[i].HeaderText + " Text(200))";
}
}
oleDbCmd.CommandText = sSql;
oleDbCmd.ExecuteNonQuery(); //写行数据
for (int j = 0; j < this.gvShowInfo.Rows.Count; j++)
{
sSql = "INSERT INTO sheet1 VALUES('";
for (int i = 0; i < gvShowInfo.Columns.Count; i++)
{
if (i < gvShowInfo.Columns.Count - 1)
sSql += gvShowInfo.Rows[j].Cells[i].Text + " ','";
else
try
{
sSql += ((System.Web.UI.WebControls.Label)gvShowInfo.Rows[j].FindControl("lblType")).Text + " ')";
}
catch { sSql += "" + " ')"; }
}
oleDbCmd.CommandText = sSql;
oleDbCmd.ExecuteNonQuery();
} //恢复到原来的页面显示方式
gvShowInfo.AllowSorting = true; //恢复分页
gvShowInfo.AllowPaging = true; //恢复排序
this.gvShowInfo.DataBind(); //再次绑定
}
catch (System.Exception ex)
{
throw ex;
}
finally
{
//断开连接
oleDbCmd.Dispose();
oleDbConn.Close();
oleDbConn.Dispose();
}
} /// <summary>
/// 数据导出
/// </summary>
private void ImportExcel()
{
try
{
//随机文件名
string FileName = "temp\\" + DateTime.Now.ToString("yyyyMMddHHmmss") + new Random().Next(9999) + ".xls";
//临时文件路径
string filePath = this.Request.PhysicalApplicationPath + FileName; //创建临时文件
CreateExcelFile(filePath); using (FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate))
{
//让用户输入下载的本地地址
Response.Clear();
Response.Buffer = true;
Response.Charset = "GB2312"; Response.AppendHeader("Content-Disposition", "attachment;filename=MonitorResult.xls");
Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
Response.ContentType = "application/ms-excel"; // 读取excel数据到内存
byte[] buffer = new byte[fs.Length - 1];
fs.Read(buffer, 0, (int)fs.Length - 1); // 写到aspx页面
Response.BinaryWrite(buffer);
Response.Flush();
this.ApplicationInstance.CompleteRequest(); //停止页的执行
fs.Close();
fs.Dispose(); //删除临时文件
File.Delete(filePath); MsgLabel1.Alert = "导出EXCE成功!";
} }
catch (Exception ex)
{
MsgLabel1.Alert = "导出EXCE失败:" + ex.Message; }
}
后缀名是xlsx的~!
/// <summary>
/// 往Excel中写入时必须有的方法
/// </summary>
/// <param name="control"></param>
public override void VerifyRenderingInServerForm(Control control)
{
// Confirms that an HtmlForm control is rendered for
//必须有的方法
} /// <summary>
/// 导入到Excel中,但是必须要有VerifyRenderingInServerForm的重载方法,要不gvone.RenderControl(htmlWrite)会报错(未在runt=server窗体中)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void btnToExcel_Click(object sender, EventArgs e)
{
Response.Clear(); //先将Response中的所有内容清除
Response.AddHeader("content-disposition", "attachment;filename=FileName.xls");//打开一个保存对话框,FileName将作为默认的Excel名称
Response.ContentType = "application/vnd.xls"; //设置流的类型,文件解析流的时候以指定的格式解析
Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312"); //编码,防止出现乱码,制定编码类型
System.IO.StringWriter stringWrite = new System.IO.StringWriter(); //实例化字符串流类
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite); //将要导入Excel中的网页内容写入字符串流中
gvone.RenderControl(htmlWrite); //将GridView内容写入字符串流中
Response.Write(stringWrite); //将流写入Response中
Response.End(); //将Response写入Excel //以下内容为分页时适用
//System.IO.StringWriter stringWrite = new System.IO.StringWriter();
//System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite); //gvone.AllowPaging = false; //如果有分页,先把分页禁用,然后重新获取下数据,将gridview写到htmlwrite中
//BindData();
//gvone.RenderControl(htmlWrite); //Response.Write(stringWrite.ToString());
//Response.End();
//gvone.AllowPaging = true;
//BindData();
}
把后缀名变成xlsxResponse.AppendHeader("Content-Disposition", "attachment;filename=MonitorResult.xlsx");
你变成XLSX,文件打不开的
excel2000,2003,2007都没有问题。
注意引入System.Reflectionusing System.Reflection;
/// <summary>
/// excel format compatiable
/// </summary>
/// <param name="ds"></param>
/// <param name="saveFileName">output file name with the physical path</param>
/// <param name="errorInfo"></param>
public static void ExportExcelMaster(System.Data.DataSet ds, string saveFileName, out string errorInfo)
{
object objApp;
object objBook; object objBooks; object objSheets; object objSheet;
object objCells;
object[] Parameters;
errorInfo = ""; try
{
// 获取Excel类型并建立其实例
Type objExcelType = Type.GetTypeFromProgID("Excel.Application");
if (objExcelType == null)
{
errorInfo = "Excel does not installed!";
return;
}
objApp = Activator.CreateInstance(objExcelType);
if (objApp == null)
{
errorInfo = "Excel can not be created on this pc!";
return;
}
//获取Workbook集
objBooks = objApp.GetType().InvokeMember("Workbooks", BindingFlags.GetProperty, null, objApp, null); //添加一个新的Workbook
objBook = objBooks.GetType().InvokeMember("Add", BindingFlags.InvokeMethod, null, objBooks, null); //获取Sheet集
objSheets = objBook.GetType().InvokeMember("Worksheets", BindingFlags.GetProperty, null, objBook, null); //获取第一个Sheet对象
Parameters = new Object[1] { 1 };
objSheet = objSheets.GetType().InvokeMember("Item", BindingFlags.GetProperty, null, objSheets, Parameters); try
{
//写入字段
for (int n= 0; n < ds.Tables[0].Columns.Count; n++)
{
Parameters = new Object[2] { 1,n + 1 };
objCells = objSheet.GetType().InvokeMember("Cells", BindingFlags.GetProperty, null, objSheet, Parameters);
//向指定单元格填写内容值
Parameters = new Object[1] { ds.Tables[0].Columns[n].ColumnName};
objCells.GetType().InvokeMember("Value", BindingFlags.SetProperty, null, objCells, Parameters);
}
//获取操作范围
for (int r = 1; r <=ds.Tables[0].Rows.Count; r++)
{
for (int i = 1; i <= ds.Tables[0].Columns.Count; i++)
{
Parameters = new Object[2] { r+1, i };
objCells = objSheet.GetType().InvokeMember("Cells", BindingFlags.GetProperty, null, objSheet, Parameters);
//向指定单元格填写内容值
Parameters = new Object[1] { ds.Tables[0].Rows[r-1][i-1].ToString() };
objCells.GetType().InvokeMember("Value", BindingFlags.SetProperty, null, objCells, Parameters);
}
}
}
catch (Exception operException)
{
//MessageBox.Show(operException.Message);
throw;
}
finally
{
//不提示保存
Parameters = new Object[1] { false };
objApp.GetType().InvokeMember("DisplayAlerts", BindingFlags.SetProperty, null, objApp, Parameters); //保存文件并退出
Parameters = new Object[1] { saveFileName};
objBook.GetType().InvokeMember("SaveAs", BindingFlags.InvokeMethod, null, objBook, Parameters);
objApp.GetType().InvokeMember("Quit", BindingFlags.InvokeMethod, null, objApp, null);
GC.Collect();
}
if (System.IO.File.Exists(saveFileName)) System.Diagnostics.Process.Start(saveFileName); //打开EXCEL
}
catch (Exception theException)
{
// String errorMessage;
errorInfo = theException.Message;
//MessageBox.Show(errorMessage, "Error");
throw;
}
}
生成如下的string:
row1column1,column2,column3
用文件流打开并写入一个.csv的文件。 这样的文件用记事本也可以看,只是cell里的内容全部用逗号隔开了而已。 Type objExcelType = Type.GetTypeFromProgID("Excel.Application");
if (objExcelType == null)
{
errorInfo = "Excel does not installed!";
//return;
}else{
System.IO.StreamWriter sr = System.IO.File.CreateText(saveFileName);
for(...){//sr.write(...)} }
Type objExcelType = Type.GetTypeFromProgID("Excel.Application");
if (objExcelType == null)
{
//errorInfo = "Excel does not installed!";
//return;
System.IO.StreamWriter sr = System.IO.File.CreateText(saveFileName);
for(...){//sr.write(...)} }
else
{
//..........
}