C#中Table匯入Excel

來源:互聯網
上載者:User

前陣子項目中遇到得問題。。。。當時在網上沒找到解決得辦法。。。今天發一個上來。。。

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Diagnostics;
using Excel;
using System.Text;

/// <summary>
/// TableToExcel

///Table匯入Excel

/// </summary>
public class TableToExcel
{
 public TableToExcel()
 {
  // TODO: 在此處添加建構函式邏輯
 }

    public void ToExcel(Table t,string title)
    {
        Excel.ApplicationClass ea = new ApplicationClass();
        Excel.Workbook wb = ea.Workbooks.Add(true);
       
      
        Excel.Worksheet ws = wb.ActiveSheet as Excel.Worksheet;
        int col = t.Rows[(t.Rows.Count - 1)].Cells.Count;
        Excel.Range range = ws.get_Range(ws.Cells[1, 1], ws.Cells[1, col]);
        range.MergeCells = true;
        range.Value2 = title;
        for (int i = 1; i <= t.Rows.Count; i++)
        {
            int count = 1;//當前列
            for (int j = 1; j <= t.Rows[i - 1].Cells.Count; j++)
            {
                //ws.Cells[i, j] = "";
                int colspan = t.Rows[i - 1].Cells[j-1].ColumnSpan;
                if (colspan == 0) colspan = 1;
                if (colspan == 1)
                {
                    ws.Cells[i + 1, count] = cleanStr(t.Rows[i - 1].Cells[j - 1].Text);
                    Range _r = ws.Cells[i+1, count] as Range;
                    Excel.Style s = _r.Style as Excel.Style;
                    s.HorizontalAlignment = XlHAlign.xlHAlignCenter;
                    count++;
                }
                else
                {
                    Excel.Range _range = ws.get_Range(ws.Cells[i+1, count], ws.Cells[i+1, count + colspan - 1]);
                    _range.MergeCells = true;
                    _range.Value2 = cleanStr(t.Rows[i - 1].Cells[j - 1].Text);
                    count = count + colspan ;
                }
               
            }
        }
        wb.SaveCopyAs(HttpContext.Current.Server.MapPath("~/Courses/temp/Excel.xls"));

    }

    protected string cleanStr(String str)
    {
        StringBuilder bs = new StringBuilder(str);
        bs = bs.Replace("<br/>", " ");
        return bs.ToString();
    }

}

 

現在存在的問題:

1、還不能控制Excel儲存格內得換行;

2、產生Excel下載到用戶端,用Excel編輯時會出現兩個介面sheet1和Excel.xls(如)

望高人指點迷津。。。。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.