日期:2014-05-18 浏览次数:20885 次
private Microsoft.Office.Interop.Excel.Application _objExcel;//Excel应用程序实例 private Microsoft.Office.Interop.Excel.Workbook _objBook;//当前操作的工作表 private Microsoft.Office.Interop.Excel.Worksheet _objSheet;//当前操作的表格 Microsoft.Office.Interop.Excel.Range range = _objSheet.UsedRange; range.Insert(Microsoft.Office.Interop.Excel.XlDirection.xlDown, Missing.Value);
------解决方案--------------------
public static bool SaveDataTableToExcel(System.Data.DataTable excelTable, string filePath) //内存中的DataSet中的数据保存到excel中
{
Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.ApplicationClass();
try
{
app.Visible = false;
Workbook wBook = app.Workbooks.Add(true);
Worksheet wSheet = wBook.Worksheets[1] as Worksheet;
if (excelTable.Rows.Count > 0)
{
int row = 0;
row = excelTable.Rows.Count;
int col = excelTable.Columns.Count;
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
string str = excelTable.Rows[i][j].ToString();
wSheet.Cells[i + 2, j + 1] = str;
}
}
}
int size = excelTable.Columns.Count;
for (int i = 0; i < size; i++)
{
wSheet.Cells[1, 1 + i] = excelTable.Columns[i].ColumnName;
}
app.DisplayAlerts = false;//设置禁止弹出保存和覆盖的询问提示框
app.AlertBeforeOverwriting = false;//保存工作簿
wBook.Save();
app.Save(filePath);//保存excel文件
app.SaveWorkspace(filePath);
app.Quit();
app = null;
return true;
}
catch (Exception err)
{
MessageBox.Show("导出Excel出错!错误原因:" + err.Message, "提示信息",
MessageBoxButtons.OK, MessageBoxIcon.Information);
return false;
}
finally
{
}
}
把内存中DataSet中的数据保存到excel文件中
------解决方案--------------------
[color=#0000FF][/color]文件上面加上
using Microsoft.Office.Interop.Excel;
using System.Data.OleDb;
当然需要添加引用;
首先新建一个Excel;
string strConn = null;
string strCommand = null;
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("~/Upload/Excel.xls") + ";Extended Properties='Excel 4.0;HDR=yes;IMEX=2'";//找到excel的表格
OleDbConnection conn = new OleDbConnection(strConn); //创建连接
conn.Open(); //此时Excel 相当于一个数据库;打开数据库;
strCommand = "INSERT INTO [Sheet1$]( 姓名,性别) values ('张小亮','男')";
OleDbCommand cmd = new OleDbCommand(strCommand, conn);
cmd.ExecuteNonQuery();
conn.Close();
注:完成对Excel 的操作,
发布后,该Excel 的权限要变为可写的,
该Excel 的表格
第一行 姓名,性别
Excel 操作时第一行的值代表的是列标题