我需要帮助。我应该如何将表中的每一行写入Excel文件?
问题#1:如何从OracleDataReader
获取每个单元格或每行的值?
问题#2:表格中的列数可能会有所不同。我应该读取每个单元格并将其写入Excel或按行吗?
代码:
try
{
string connectionString = ConfigurationManager.ConnectionStrings["OracleConnectionString"].ConnectionString;
OracleConnection connection = new OracleConnection();
connection.Open();
if(connection.ToString().Equals("Open"))
{
OracleCommand cmd = new OracleCommand();
cmd.Connection = connection;
cmd.Parameters.Add (dict_name);
cmd.CommandText = "SELECT * from :dict_name";
cmd.CommandType = CommandType.Text;
OracleDataReader dataReader = cmd.ExecuteReader();
while (dataReader.Read())
{
}
}
connection.Close();
}
catch (OracleException e)
{
if (e.ErrorCode != 2000)
{
Console.WriteLine("Oracle Error -> {0} {1}", DateTime.Now.ToString("dd mm yyyy HH:mm:ss"), e.StackTrace);
}
}
catch (Exception e)
{
Console.WriteLine("Erorr -> {0} {1}", DateTime.Now.ToString("dd mm yyyy HH:mm:ss"), e.StackTrace);
}
答案 0 :(得分:0)
所以我明白了。这是现在为我工作的代码。我在数据库中使用不同的表进行了尝试。
问题:任何人都知道如何从excel动态读取并将数据加载到数据库中?我的意思是,动态构造INSERT命令
[WebMethod]
public string dictToExcel(string dict_name)
{
string connectionString = ConfigurationManager.ConnectionStrings["OracleConnection"].ConnectionString;
OracleConnection connection = new OracleConnection(connectionString);
try
{
connection.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = connection;
cmd.CommandText = "SELECT * from " + dict_name;
cmd.CommandType = CommandType.Text;
OracleDataReader dataReader = cmd.ExecuteReader();
IWorkbook workbook;
workbook = new XSSFWorkbook();
ISheet sheet = workbook.CreateSheet("Sheet 1");
int b = 0;
while (dataReader.Read())
{
int n = 0;
IRow row = sheet.CreateRow(b);
while (n < dataReader.FieldCount)
{
ICell cell = row.CreateCell(n);
String columnName = dataReader.GetValue(n).ToString();
cell.SetCellValue(columnName);
n++;
}
b++;
}