- 爱易网页
-
ASP.NET教程
- 初做,C#操作Excel,请给具体例子或资料,多谢,例子合适马上结贴
日期:2014-05-18 浏览次数:20548 次
初做,C#操作Excel,请给具体例子或资料,谢谢,在线等,例子合适马上结贴
初做,C#操作Excel,请给具体例子或资料,谢谢,在线等,例子合适马上结贴
------解决方案--------------------
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0; " + "Data Source= " + excel表 + "; " + "Extended Properties=Excel 8.0; ";
OleDbConnection conn = new OleDbConnection(strConn);
conn.Open()
strExcel = "select * from [Sheet1$] ";
// MessageBox.Show(strExcel);
myCommand = new OleDbDataAdapter(strExcel, strConn);
ds = new DataSet();
myCommand.Fill(ds, "[Sheet1$] ");
conn.Close();
conn.Dispose();
------解决方案--------------------
给你一个类,揭贴吧!
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Office.Interop.Excel;
using System.Windows.Forms;
namespace DataAccess
{
public class ExcelAccess
{
private Microsoft.Office.Interop.Excel.Application MyExcel;
private object missing = System.Reflection.Missing.Value;
public int MaxColIndex
{
get
{
return MyExcel.Cells.Rows.Worksheet.UsedRange.Cells.Columns.Count;
}
}
public int MaxRowIndex
{
get
{
return MyExcel.Cells.Columns.Worksheet.UsedRange.Rows.Count;
}
}
public int ExcelOpen(string fileName)
{
try
{
MyExcel = new ApplicationClass();
if (MyExcel == null)
{
MessageBox.Show("Excel 程序无法启动!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
return -2;
}
MyExcel.Workbooks.Open(fileName, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + "\n" + ex.ToString(), "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
return -1;
}
return 1;
}
public int ExcelOpen(string fileName,Boolean AutoCreateFile)
{
try
{
MyExcel = new ApplicationClass();
if (MyExcel == null)
{
MessageBox.Show("Excel 程序无法启动!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
return -2;
}
if(FileAccessExt.FileExist(fileName))
MyExcel.Workbooks.Open(fileName, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing);
else
{
//create file
Worksheet mysheet=null;
MyExcel.Workbooks.Add(missing);
mysheet = (Worksheet)MyExcel.ActiveWorkbook.ActiveSheet;
//mysheet =(Worksheet)MyExcel.ActiveWorkbook.Worksheets.Add(missing, missing, 1, missing);
mysheet.SaveAs(fileName,missing,missing,missing,missing,missing,missing,missing,missing,missing);