繁体   English   中英

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

[英]Writing to existing excel table using oledb - C#

目前,我正在使用以下代码:

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 ,它将起作用,它将创建它,然后插入目标行。 但是,当我删除“创建表”命令并仅使用插入命令时,它将无法工作并说表table1已经存在。 如何使用oldeb将行插入到现有表(工作表)的末尾(附加行)?

我建议使用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;
        }
    }

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();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM