C# DataTable与Excel读取与导出
阅读原文时间:2023年07月10日阅读:1

///

/// Excel->DataTable ///
/// Excel文件路径
public static DataTable ReadExcel(string filePath)
{
IWorkbook iwkX;
using (FileStream fs = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
iwkX = WorkbookFactory.Create(fs);
fs.Close();
}
//sheet
DataTable dt = new DataTable();
for (int h = ; h < iwkX.NumberOfSheets; h++)
{
ISheet sheet = iwkX.GetSheetAt(h);
var rows = sheet.GetRowEnumerator();
bool isMove = rows.MoveNext();
//循环sheet
if (isMove)
{
var Cols = (IRow)rows.Current;
dt.TableName = sheet.SheetName;
for (int i = ; i < Cols.LastCellNum; i++)
{
string str = Cols.GetCell(i).ToString();
dt.Columns.Add(Cols.GetCell(i).ToString());
}
while (rows.MoveNext())
{
var row = (IRow)rows.Current;
var dr = dt.NewRow();
for (int i = ; i < row.LastCellNum; i++)
{
var cell = row.GetCell(i);
if (cell == null)
{
dr[i] = "";
}
else
{
string strdr = cell.ToString();
dr[i] = cell.ToString();
}
}
dt.Rows.Add(dr);
}
}
}

        return dt;  
    }

    /// <summary>  
    /// DataTable导出到Excel  
    /// </summary>  
    /// <param name="dt">DataTable</param>  
    /// <param name="array">首行数组</param>  
    /// <param name="fileFullName">文件名</param>  
    public static void ExportToExcel(DataTable dt, string\[\] array, string fileFullName)  
    {  
        #region  
        XSSFWorkbook workbook = new XSSFWorkbook();  
        FileStream fs = new FileStream(fileFullName, FileMode.OpenOrCreate, FileAccess.ReadWrite);  
        ISheet sheet = workbook.CreateSheet("Sheet0");  
        IRow row;  
        row = sheet.CreateRow();

        for (int i = ; i < array.Length; i++)  
        {  
            row.CreateCell(i).SetCellValue(array\[i\]);  
        }

        for (int i = ; i < dt.Rows.Count; i++)  
        {  
            row = sheet.CreateRow(i + );

            for (int j = ; j < dt.Columns.Count; j++)  
            {  
                row.CreateCell(j).SetCellValue(dt.Rows\[i\]\[j\].ToString());  
            }  
        }  
        workbook.Write(fs); //写入到excel

        #endregion  
        // MessageBox.Show("导出成功!");  
    }

手机扫一扫

移动阅读更方便

阿里云服务器
腾讯云服务器
七牛云服务器

你可能感兴趣的文章