国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > C# > 正文

C# WinForm導出Excel方法介紹

2020-01-24 03:02:40
字體:
來源:轉載
供稿:網友

.NET開發人員首選的方法,通過COM組件調用Office軟件本身來實現文件的創建和讀寫,但是數據量較大的時候異常緩慢;如下代碼所示已經做了優化,將一個二維對象數組賦值到一個單元格區域中(下面的代碼中只能用于導出列數不多于26列的數據導出):

Office PIA

復制代碼 代碼如下:

public static void ExportToExcel(DataSet dataSet, string outputPath)
{
    Excel.ApplicationClass excel = new Excel.ApplicationClass();
    Excel.Workbook workbook = excel.Workbooks.Add(Type.Missing);
    int sheetIndex = 0;
    foreach (System.Data.DataTable dt in dataSet.Tables)
    {
        object[,] data = new object[dt.Rows.Count + 1, dt.Columns.Count];
        for (int j = 0; j < dt.Columns.Count; j++)
        {
            data[0, j] = dt.Columns[j].ColumnName;
        }
        for (int j = 0; j < dt.Columns.Count; j++)
        {
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                data[i + 1, j] = dt.Rows[i][j];
            }
        }
        string finalColLetter = string.Empty;

        string colCharset = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        int colCharsetLen = colCharset.Length;
        if (dt.Columns.Count > colCharsetLen)
        {
            finalColLetter = colCharset.Substring(
                (dt.Columns.Count - 1) / colCharsetLen - 1, 1);
        }
        finalColLetter += colCharset.Substring(
                (dt.Columns.Count - 1) % colCharsetLen, 1);

        Excel.Worksheet sheet = (Excel.Worksheet)workbook.Sheets.Add(
            workbook.Sheets.get_Item(++sheetIndex),
            Type.Missing, 1, Excel.XlSheetType.xlWorksheet);
        sheet.Name = dt.TableName;
        string range = string.Format("A1:{0}{1}", finalColLetter, dt.Rows.Count + 1);
        sheet.get_Range(range, Type.Missing).Value2 = data;
        ((Excel.Range)sheet.Rows[1, Type.Missing]).Font.Bold = true;
    }
    workbook.SaveAs(outputPath, Excel.XlFileFormat.xlWorkbookNormal, Type.Missing,
        Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlExclusive,
        Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
    workbook.Close(true, Type.Missing, Type.Missing);
    workbook = null;
    excel.Quit();
    KillSpecialExcel(excel);
    excel = null;
    GC.Collect();
    GC.WaitForPendingFinalizers();
}

[DllImport("user32.dll", SetLastError = true)]
static extern int GetWindowThreadProcessId(IntPtr hWnd, out int processId);

static void KillSpecialExcel(Excel.Application app)
{
    try
    {
        if (app != null)
        {
            int processId;
            GetWindowThreadProcessId(new IntPtr(app.Hwnd), out processId);
            System.Diagnostics.Process.GetProcessById(processId).Kill();
        }
    }
    catch (Exception ex)
    {
        throw ex;
    }
}

文件流

這種方法的效率明顯高于第一種,而且也不需要安裝Office,但是導出的xls文件并不符合Excel的格式標準,在打開生成的xls文件時會提示:The file you are trying to open is in a different format that specified by the file extension. Verify that the file is not corrupted and is from a trusted source before opening the file.

復制代碼 代碼如下:

public static void ExportToExcel(System.Data.DataSet ds, string path)
{
    StreamWriter sw = null;
    try
    {
        long totalCount = ds.Tables[0].Rows.Count;
        sw = new StreamWriter(path, false, Encoding.Unicode);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < ds.Tables[0].Columns.Count; i++)
        {
            sb.Append(ds.Tables[0].Columns[i].ColumnName + "/t");
        }
        sb.Append(Environment.NewLine);
        for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
        {
            for (int j = 0; j < ds.Tables[0].Columns.Count; j++)
            {
                sb.Append(ds.Tables[0].Rows[i][j].ToString() + "/t");
            }
            sb.Append(Environment.NewLine);
        }
        sw.Write(sb.ToString());
        sw.Flush();
    }
    catch (IOException ioe)
    {
        throw ioe;
    }
    finally
    {
        if (sw != null)
        {
            sw.Close();
        }
    }
}

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 祁连县| 个旧市| 临湘市| 瑞金市| 平顶山市| 晴隆县| 舞阳县| 仁布县| 彩票| 宁化县| 根河市| 奉贤区| 临朐县| 聂拉木县| 郁南县| 三亚市| 公安县| 山丹县| 太湖县| 交口县| 鹤山市| 鹤岗市| 香格里拉县| 沛县| 三穗县| 长岭县| 和平县| 内江市| 桦南县| 如皋市| 阿图什市| 天气| 林西县| 石首市| 祁连县| 依安县| 文登市| 大足县| 梨树县| 丹凤县| 砚山县|