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

C# 使用oledb-C写入现有excel表#,c#,oledb,C#,Oledb,目前我正在使用以下代码: private void WriteExcelFile() { string connectionString = GetConnectionString(); using (OleDbConnection conn = new OleDbConnection(connectionString)) { conn.Open(); OleDbCommand cmd = new OleDbCommand();

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

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

如果没有
表1
,它将工作,它将创建它,然后插入目标行。但是,当我删除createtable命令并使用justinsert时,它将不起作用,并告诉我
table1
已经存在。如何使用oldeb在末尾(追加行)向现有表(工作表)插入行

Oledb没有那么灵活,您可以改用library

下面是一个例子

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

Oledb并没有那个么灵活,你们可以用library来代替

下面是一个例子

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

我建议NOPI,我认为它比EPPlus更好

下面是将datatable转换为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;
        }
    }
公共类工具
{
公共静态字节[]WriteExcel(DataTable dtExport,字符串[]头=null,字符串[]excludeColumns=null,bool rtl=true)
{
MemoryStream ms=新的MemoryStream();
尝试
{
XSSFWorkbook XSSFWorkbook=新XSSFWorkbook();
ISHET表=空;
//-----------创建样式和字体
var hFont=xssf工作簿.CreateFont();
hFont.FontHeightInPoints=11;
hFont.FontName=“Tahoma”;
var defaultStyle=xssf工作簿.CreateCellStyle();
defaultStyle.SetFont(hFont);
var defaultHeaderStyle=xssf工作簿.CreateCellStyle();
defaultHeaderStyle.FillBackgroundColor=NPOI.HSSF.Util.HSSFColor.Blue格雷.Index;
defaultHeaderStyle.SetFont(hFont);
如果(xssfWorkbook.NumberOfSheets==0)
{
sheet=xssfWorkbook.CreateSheet(String.IsNullOrWhiteSpace(dtExport.TableName)-“ExportReport”:dtExport.TableName);
sheet.IsRightToLeft=真;
sheet.CreateRow(0);
}
if(标题!=null)
{
for(int index=0;index
我建议NOPI,我认为它比EPPlus好

下面是将datatable转换为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;
        }
    }
公共类工具
{
公共静态字节[]WriteExcel(DataTable dtExport,字符串[]头=null,字符串[]excludeColumns=null,bool rtl=true)
{
MemoryStream ms=新的MemoryStream();
尝试
{
XSSFWorkbook XSSFWorkbook=新XSSFWorkbook();
ISHET表=空;
//-----------创建样式和字体
var hFont=xssf工作簿.CreateFont();
hFont.FontHeightInPoints=11;
hFont.FontName=“Tahoma”;
var defaultStyle=xssf工作簿.CreateCellStyle();
defaultStyle.SetFont(hFont);
var defaultHeaderStyle=xssf工作簿.CreateCellStyle();
defaultHeaderStyle.FillBackgroundColor=NPOI.HSSF.Util.HSSFColor.Blue格雷.Index;
defaultHeaderStyle.SetFont(hFont);
如果(xssfWorkbook.NumberOfSheets==0)
{
sheet=xssfWorkbook.CreateSheet(String.IsNullOrWhiteSpace(dtExport.TableName)-“ExportReport”:dtExport.TableName);
sheet.IsRightToLeft=真;
sheet.CreateRow(0);
}
if(标题!=null)
{
for(int index=0;index