使用oledb写入现有的excel表 - C#

时间:2017-04-29 06:26:47

标签: c# oledb

目前我正在使用此代码:

private void WriteExcelFile()
{
    string connectionString = GetConnectionString();

    using (OleDbConnection conn = new OleDbConnection(connectionString))
    {
        conn.Open();
        OleDbCommand cmd = new OleDbCommand();
        cmd.Connection = conn;

        cmd.CommandText = "CREATE TABLE [table1] (id INT, name VARCHAR, datecol DATE );";
        cmd.ExecuteNonQuery();

        cmd.CommandText = "INSERT INTO [table1](id,name,datecol) VALUES(1,'AAAA','2014-01-01');";
        cmd.ExecuteNonQuery();

        conn.Close();
    }
}

如果没有table1它会工作,它会创建它然后插入目标行。但是当我删除Create table命令并仅使用插入时,它将无效并告诉我table1已经存在。如何使用oldeb将行插入到现有表(工作表)的末尾(追加行)?

2 个答案:

答案 0 :(得分:2)

我建议NOPI,在我看来比EPPlus更好

将数据表转换为excel的示例代码在这里

public class ExcelTools
{
    public static byte[] WriteExcel(DataTable dtExport, string[] header = null, string[] excludeColumns = null, bool rtl = true)
    {
        MemoryStream ms = new MemoryStream();
        try
        {
            XSSFWorkbook xssfWorkbook = new XSSFWorkbook();
            ISheet sheet = null;
            //-----------Create Style And Font
            var hFont = xssfWorkbook.CreateFont();
            hFont.FontHeightInPoints = 11;
            hFont.FontName = "Tahoma";
            var defaultStyle = xssfWorkbook.CreateCellStyle();
            defaultStyle.SetFont(hFont);
            var defaultHeaderStyle = xssfWorkbook.CreateCellStyle();
            defaultHeaderStyle.FillBackgroundColor = NPOI.HSSF.Util.HSSFColor.BlueGrey.Index;
            defaultHeaderStyle.SetFont(hFont);
            if (xssfWorkbook.NumberOfSheets == 0)
            {
                sheet = xssfWorkbook.CreateSheet(String.IsNullOrWhiteSpace(dtExport.TableName) ? "ExportReport" : dtExport.TableName);
                sheet.IsRightToLeft = true;
                sheet.CreateRow(0);
            }
            if (header != null)
            {
                for (int index = 0; index < header.Length; index++)
                {
                    var strHeader = header[index];
                    sheet.GetRow(0).CreateCell(index).SetCellValue(header[index]);
                    sheet.GetRow(0).GetCell(index).CellStyle = defaultHeaderStyle;
                }
            }
            else
            {
                int index = 0;
                foreach (DataColumn col in dtExport.Columns)
                {
                    if (excludeColumns != null && excludeColumns.Contains(col.ColumnName))
                        continue;
                    sheet.GetRow(0).CreateCell(index).SetCellValue(col.ColumnName);
                    index++;
                }

            }


            sheet = xssfWorkbook.GetSheetAt(0);
            int indexRow = sheet.LastRowNum + 1;

            for (; indexRow < dtExport.Rows.Count + 1; indexRow++)
            {
                sheet.CreateRow(indexRow);
                int index = 0;
                foreach (DataColumn col in dtExport.Columns)
                {
                    if (excludeColumns != null && excludeColumns.Contains(col.ColumnName))
                        continue;
                    sheet.GetRow(indexRow).CreateCell(index).SetCellValue(dtExport.Rows[indexRow - 1][col.ColumnName].ToStringTD());
                    sheet.GetRow(indexRow).GetCell(index).CellStyle = defaultStyle;
                    index++;
                }
            }
            for (int index = 0; index < sheet.GetRow(0).Cells.Count; index++)
            {
                sheet.AutoSizeColumn(index);
            }
            xssfWorkbook.Write(ms);
            return ms.ToArray();

        }
        catch (Exception ex)
        {
            return null;
        }
    }

答案 1 :(得分:1)

Oledb不够灵活,您可以使用EPPlus库。

这是一个例子。

using(var package = new ExcelPackage(new FileInfo(@"c:\temp\tmp.xlsx")))
{
   // calculate all formulas in the workbook
   package.Workbook.Calculate();
   // calculate one worksheet
   package.Workbook.Worksheets["my sheet"].Calculate();
  // calculate a range
  package.Workbook.Worksheets["my sheet"].Cells["A1"].Calculate();
}