asp.net 读取excel

方法一:

Create a reference in your project to Excel Objects Library.  The excel object library can be added in the COM tab of adding reference dialog. I hope the following code in your menu click event method will help you a lot to achieve your need.

  this .openFileDialog1.FileName = "*.xls";
 
if ( this .openFileDialog1.ShowDialog() == DialogResult.OK)
   {
      Excel.Workbook theWorkbook = ExcelObj.Workbooks.Open(
         openFileDialog1.FileName, 0, true , 5,
          "", "",
true , Excel.XlPlatform.xlWindows, "/t", false , false ,
          0,
true );
 
     Excel.Sheets sheets = theWorkbook.Worksheets;
     Excel.Worksheet worksheet = (Excel.Worksheet)sheets.get_Item(1);
     for ( int i = 1; i <= 10; i++)
     {
     Excel.Range range = worksheet.get_Range("A"+i.ToString(), "J" + i.ToString());
     System.Array myvalues = (System.Array)range.Cells.Value;

     string [] strArray = ConvertToStringArray(myvalues);
     
}
}

方法二:

f you don't want to use the Excel COM objects, you can use OleDb. It takes a little setup in your Excel document. Basically, you need to define "named objects" in Excel that are synonymous to tables in a database. The first row of the named object are the column headers. To set up a named object, first select the range of cells (your "table," with the first row being the column headers), then go to menu Insert->Names->Define. Name your object and press "Add." Now you have an object which can be read by ADO.NET.

Now for the C# (this example assumes I have an Excel file at C:/Book1.xls and a named object in this workbook called "MyObject"):





using System.Data;
using System.Data.OleDb;
...
OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:/Book1.xls;Extended Properties=Excel 8.0");
OleDbDataAdapter da = new OleDbDataAdapter("select * from MyObject", con);
DataTable dt = new DataTable();
da.Fill(dt);

 


You can use SQL to query the data in your named object.

方法三:

http://www.codeproject.com/KB/office/ExcelReader.aspx

上篇文章有一些错误,更正如下:

sample code:

WCF部分:
using ExcelLibrary.SpreadSheet;
using ExcelLibrary.CompoundDocumentFormat;
using ExcelLibrary.BinaryFileFormat;
[DataContract]
public class ExcelGridData
{
    public ExcelGridData()
    {
        m_Header = new List<string>();
        m_Data = new List<List<string>>();
    }
    [DataMember]
    public List<string> m_Header;
    [DataMember]
    public List<List<string>> m_Data;
}

 

 

        string filePath = HostingEnvironment.MapPath("~/upload/Book1.xls");
        //Stream fileStream = File.OpenRead(filePath);

        CompoundDocument doc = CompoundDocument.Read(filePath);
        if (doc == null) throw new Exception("Invalid Excel file");
        byte[] bookdata = doc.GetStreamData("Workbook");
        Workbook book = WorkbookDecoder.Decode(new MemoryStream(bookdata));
        Worksheet sheet = book.Worksheets[0];

        ExcelGridData rtval = new ExcelGridData();
        for (int rowIndex = sheet.Cells.FirstRowIndex; rowIndex <= sheet.Cells.LastRowIndex; rowIndex++)
        {
            Row row = sheet.Cells.GetRow(rowIndex);
            if (rowIndex == 0)
            {
                for (int colIndex = row.FirstColIndex; colIndex <= row.LastColIndex; colIndex++)
                {
                    rtval.m_Header.Add("A[" + rowIndex.ToString() + "]");
                }
            }
            List<string> tmprow = new List<string>();
            for (int colIndex = row.FirstColIndex; colIndex <= row.LastColIndex; colIndex++)
            {
                Cell cell = row.GetCell(colIndex);
                tmprow.Add(cell.StringValue);
            }
            rtval.m_Data.Add(tmprow);
        }
        return rtval;

 

Client 部分:


            List<ObservableCollection<string>> tmpdata = rt.m_Data.ToList();
            int iter = 0;
            foreach (ObservableCollection<string> tmprow in tmpdata)
            {
                BindableDataGrid.Data.DataRow dr = new BindableDataGrid.Data.DataRow();
                if (iter >100)
                {
                    break;
                }
                int i = 0;
                foreach (string tmpitem in tmprow.ToList())
                {
                    dr["col" + i.ToString()] = tmpitem;
                    i++;
                }
                dt.Rows.Add(dr);
                iter++;
            }
            DataSet ds = new DataSet("MyDataSet");
            ds.Tables.Add(dt);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
ASP.NET中,我们可以使用多种方法来导出Excel文件。 一种常用的方法是使用Microsoft的Interop库,将数据导出为Excel文件。我们首先需要安装Excel程序,并确保机器上已经安装了Microsoft Office。然后,我们可以通过创建一个Excel Application对象来访问Excel应用程序。我们可以创建一个工作簿(Workbook)和一个工作表(Worksheet),然后将数据写入工作表。最后,我们可以使用SaveAs方法将工作簿保存为Excel文件。这种方法的缺点是需要机器上安装Office,而且在服务器上可能会遇到权限问题。 另一种方法是使用开源的库,比如EPPlus。EPPlus是一个用于处理Excel文件的.Net库,可以在不安装Office的情况下读取和写入Excel文件。我们可以使用EPPlus库创建一个Excel包(ExcelPackage)对象,并创建一个工作表。然后,我们可以在工作表中写入数据并保存为Excel文件。这种方法不仅适用于ASP.NET,而且在服务器上也没有Office依赖的问题。 还有一种简单的方法是将数据导出为CSV(逗号分隔值)文件。CSV文件是文本文件,使用逗号分隔每个值。我们可以使用StreamWriter类创建一个文本文件,并将数据按照CSV格式写入文件。CSV文件可以在Excel中直接打开,并且不需要额外的库或软件。 以上是ASP.NET导出Excel的几种方法。根据具体需求和平台限制,我们可以选择适合的方法来导出Excel文件。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值